在 Ruby 中跳过额外的关键字参数
Skipping extra keyword arguments in Ruby
我定义了一个方法:
def method(one: 1, two: 2)
[one, two]
end
当我这样称呼它时:
method one: 'one', three: 'three'
我得到:
ArgumentError: unknown keyword: three
我不想从散列中一个一个地提取所需的键或排除额外的键。除了像这样定义方法之外,有没有办法规避这种行为:
def method(one: 1, two: 2, **other)
[one, two, other]
end
如果不想other
写成**other
,可以省略。
def method(one: 1, two: 2, **)
[one, two]
end
解决这个问题的一种常见方法是使用选项哈希。你会经常看到这个:
def method_name(opts={})
one = opts[:one] || 1 # if caller doesn't send :one, provide a default
two = opts[:two] || 2 # if caller doesn't send :two, provide a default
# etc
end
不确定它是否适用于 ruby 2.0,但您可以尝试使用 **_
忽略其他参数。
def method(one: 1, two: 2, **_)
在内存使用和其他方面,我相信这和 **other
没有区别,但下划线是 ruby.
中静音参数的标准方式
我定义了一个方法:
def method(one: 1, two: 2)
[one, two]
end
当我这样称呼它时:
method one: 'one', three: 'three'
我得到:
ArgumentError: unknown keyword: three
我不想从散列中一个一个地提取所需的键或排除额外的键。除了像这样定义方法之外,有没有办法规避这种行为:
def method(one: 1, two: 2, **other)
[one, two, other]
end
如果不想other
写成**other
,可以省略。
def method(one: 1, two: 2, **)
[one, two]
end
解决这个问题的一种常见方法是使用选项哈希。你会经常看到这个:
def method_name(opts={})
one = opts[:one] || 1 # if caller doesn't send :one, provide a default
two = opts[:two] || 2 # if caller doesn't send :two, provide a default
# etc
end
不确定它是否适用于 ruby 2.0,但您可以尝试使用 **_
忽略其他参数。
def method(one: 1, two: 2, **_)
在内存使用和其他方面,我相信这和 **other
没有区别,但下划线是 ruby.