实际发生了什么:
# Assign a value of "meh" to scope, which is OUTSIDE meth and equivalent to
# scope = "meth"
# meth(1, scope)
meth(1, scope = "meh")
# Ruby takes the return value of assignment to scope, which is "meh"
# If you were to run `puts scope` at this point you would get "meh"
meth(1, "meh")
# id = 1, options = "meh", scope = "scope"
puts options
# => "meh"
不支持命名参数*(请参阅下面的 2.0 更新)。您所看到的只是分配"meh"
给scope
作为options
值传递的结果meth
。当然,该赋值的值是"meh"
。
有几种方法可以做到:
def meth(id, opts = {})
# Method 1
options = opts[:options] || "options"
scope = opts[:scope] || "scope"
# Method 2
opts = { :options => "options", :scope => "scope" }.merge(opts)
# Method 3, for setting instance variables
opts.each do |key, value|
instance_variable_set "@#{key}", value
# or, if you have setter methods
send "#{key}=", value
end
@options ||= "options"
@scope ||= "scope"
end
# Then you can call it with either of these:
meth 1, :scope => "meh"
meth 1, scope: "meh"
等等。但是,由于缺少命名参数,它们都是解决方法。
编辑(2013 年 2 月 15 日):
* 好吧,至少在即将到来的支持关键字参数的 Ruby 2.0 之前!在撰写本文时,它位于候选版本 2 上,即正式发布之前的最后一个版本。虽然您需要了解上述方法才能使用 1.8.7、1.9.3 等,但那些能够使用较新版本的人现在有以下选项:
def meth(id, options: "options", scope: "scope")
puts options
end
meth 1, scope: "meh"
# => "options"