This question already has an answer here:
- No named parameters in Ruby? 4 answers
I wonder why named parameters don't work as I expect.
def my_method(var1, var2 = 1, var3 = 10)
puts var1, var2, var3
end
my_method(999, var3 = 123)
The output
999
123
10
instead of (at least, as I guess should be):
999
1
123
So, what should I do to use named parameters?
P.S. When I use the hash, it's not what I'm looking for yet:
def my_method(var1, vars = {var2: 1, var3: 10} )
puts var1, vars[:var2], vars[:var3]
end
my_method(999, var3: 123)
999
123
my_method(999, var2: 111, var3: 123)
999
111
123
my_method(999)
999
1
10
So I have to override each value of vars
or don't override them at all. Is there any more convenient way?
You can use this
call using
or
Ruby 2.0.0 is released, now you can use named parameters.
The result:
Or another example:
You can also play with something like this:
In ruby
my_method(999, var3 = 123)
means, assignvar3
the value123
and pass it tomy_method
.There is no concept of named parameters, however, you can use a hash as an argument to
my_method
such as:Then you can call it with:
which will print
1, 2, 3
, becauseb: 2, c: 3, a: 1
is inferred to be a hash by ruby. You can explicitly indicate the hash as well with:As pointed out, Ruby does not have keyword arguments (yet, they are coming in 2.0). To achieve what you are trying to do, an
options
hash is a very common Ruby idiom.Note that using
options.fetch(:key, default)
rather thanoptions[:key] || default
is frequently preferable because it allows you to explicitly specify falsy values (iefalse
andnil
).You can even pass a block to
fetch
which allows you to defer computation of the default value: