Given the following method which takes two keyword arguments begin and end:
def make_range(begin: 0, end: -1)
# ...
end
I can call this method without problem:
make_range(begin: 2, end: 4)
But how do I use the keyword arguments when implementing the method, given that both happen to be Ruby keywords?
This obviously doesn't work:
def make_range(begin: 0, end: -1)
begin..end
end
Note that this is just an example, the problem applies to all keywords, not just begin and end.
Please find other variable names. (e.g. min and max or range_begin and range_end)
You can use binding.local_variable_get :
def make_range(begin: 0, end: 10)
(binding.local_variable_get(:begin)..binding.local_variable_get(:end))
end
p make_range(begin: 10, end: 20)
#=> 10..20
You can also use keyword arguments.
def make_range(**params)
(params.fetch(:begin, 0)..params.fetch(:end, 10))
end
p make_range
#=> 0..10
p make_range(begin: 5)
#=> 5..10
p make_range(end: 5)
#=> 0..5
p make_range(begin: 10, end: 20)
#=> 10..20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With