How to deal with key arguments that are keywords in Ruby?

Given the following method, which takes two arguments from the begin and end :

 def make_range(begin: 0, end: -1) # ... end 

I can call this method without problems:

 make_range(begin: 2, end: 4) 

But how to use keyword arguments when implementing a method, given that both of them are Ruby keywords ?

This clearly does not work:

 def make_range(begin: 0, end: -1) begin..end end 

Please note that this is just an example, the problem applies to all keywords, not just begin and end .

+5
source share
1 answer

A simple solution

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

Difficult decisions

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 
+7
source

Source: https://habr.com/ru/post/1263200/


All Articles