Ruby使用关键字命名参数

时间:2015-01-09 09:00:08

标签: ruby

我喜欢使用方法签名,如:

def register(something, on:, for:)

这有效,但我无法解决如何使用“for”而不会导致语法错误!相当烦人,有人知道解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

在Ruby中, for 是一个保留关键字 - 看起来你不能以其他方式使用它们来实现它们的使用方式。 这是保留关键字的全部目的。

在Ruby中保留关键字的其他资源:

UPD

Actualy,您仍然可以使用:for 符号作为哈希中的键(例如,选项哈希),因此,您可以这样写:

def test(something, options = {})
  puts something
  puts options.values.join(' and ')
end 

它就像魅力一样:

[4] pry(main)> test 'arguments', :for => :lulz, :with => :care, :while => 'you are writing code' 
arguments
lulz and care and you are writing code

答案 1 :(得分:2)

binding.local_variable_get(:for)

是我想的一种方式。我认为只适用于红宝石2.1+。

注意:不要这样做,我只对你如何绕过它感兴趣,你可能只需要调用你的命名参数:)

答案 2 :(得分:1)

问题不在于您发布的方法定义行,问题是在方法体内使用for变量。由于for是保留字,因此不能将其用作普通变量名,但可以将其用作散列的一部分。在您的情况下,这意味着您必须使用任意关键字参数(**opts),但您可以在方法调用中使用keyword_argument for:。如果密钥不存在,您可能需要提出ArgumentError来模拟您在上面发布的方法签名的行为。

def register(something, on:, **opts)
  raise ArgumentError, 'missing keyword: for' unless opts.has_key?(:for)
  for_value = opts[:for]

  puts "registering #{something} on #{on} for #{for_value}"
end

register 'chocolate chips', on: 'cookie'
# ArgumentError: missing keyword: for

register 'chocolate chips', on: 'cookie', for: 'cookie monster'
# registering chocolate chips on cookie for cookie monster