实际发生的情况:
meth(1, scope = "meh")
meth(1, "meh")
puts options
没有命名参数的支持(请参见下面的2.0更新)。您看到的只是将"meh"
分配给scope
,作为meth
中传递的options
值的结果。当然,该分配的值是"meh"
。
有几种方法可以做到这一点:
def meth(id, opts = {})
options = opts[:options] || "options"
scope = opts[:scope] || "scope"
opts = { :options => "options", :scope => "scope" }.merge(opts)
opts.each do |key, value|
instance_variable_set "@#{key}", value
send "#{key}=", value
end
@options ||= "options"
@scope ||= "scope"
end
meth 1, :scope => "meh"
meth 1, scope: "meh"
等等。它们都是解决方案,但都是因为缺少命名参数而产生的。
编辑(2013年2月15日):
* 好消息是,至少在即将到来的Ruby 2.0之前,它支持关键字参数!截至本文撰写时,它已经发布了RC2版本,这是正式发布之前的最后一个版本。虽然您需要了解上面介绍的方法才能使用1.8.7、1.9.3等版本,但那些能够使用更新版本的人现在有以下选项:
def meth(id, options: "options", scope: "scope")
puts options
end
meth 1, scope: "meh"