简体   繁体   English

如何处理碰巧在Ruby中成为关键字的关键字参数?

[英]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 : 给定以下方法,它接受两个关键字参数beginend

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 ? 但是在实现方法时我如何使用关键字参数,因为两者都恰好是Ruby 关键字

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 . 请注意,这只是一个示例,该问题适用于所有关键字,而不仅仅是beginend

Easy solution 轻松解决方案

Please find other variable names. 请查找其他变量名称。 (eg min and max or range_begin and range_end ) (例如minmaxrange_beginrange_end

Convoluted solutions 复杂的解决方案

local_variable_get local_variable_get

You can use binding.local_variable_get : 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM