Notice that all arguments are evaluated prior to a method call. If you do f(b = 3)
, then value assignment b = 3
takes place first, whose return value is 3
, and that is used as the argument, so it is the same as doing f(3)
. Since you provide only one argument, it will be interpreted as the first argument a
, and the default value would be used for b
.
You are using the wrong construction. This is the way to do it:
def f a: 1, b: 2
puts "#{a} #{b}"
end
f(b: 3)
# => 1 3
It is using keyword arguments introduced in Ruby 2.0, as is explained in a page that Arup's answer links to.
Here is a workaround for Ruby 1.8, Ruby 1.9.
def f h = {}
h[:a] ||= 1
h[:b] ||= 2
puts "#{h[:a]} #{h[:b]}"
end
f(:b => 3) # Ruby 1.8
f(b: 3) # Ruby 1.9
# => 1 3