Stefan
Stefan

Reputation: 114138

How to deal with keyword arguments that happen to be keywords in Ruby?

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.

Upvotes: 5

Views: 95

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54213

Easy solution

Please find other variable names. (e.g. min and max or range_begin and range_end)

Convoluted solutions

local_variable_get

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

Keyword arguments / Hash parameter

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

Upvotes: 7

Related Questions