Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 559
Stefan Avatar asked Jan 23 '17 10:01

Stefan


1 Answers

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
like image 170
Eric Duminil Avatar answered Oct 09 '22 15:10

Eric Duminil