34

这太简单了,我简直不敢相信它抓住了我。

def meth(id, options = "options", scope = "scope")
  puts options
end

meth(1, scope = "meh")

-> "meh"

我倾向于使用散列作为参数选项,只是因为它是牛群的做法——而且它很干净。我以为这是标准。今天,经过大约 3 个小时的 bug 搜寻,我发现我碰巧使用的这个 gem 有一个错误,假设命名参数将被尊重。他们不是。

所以,我的问题是:在 Ruby (1.9.3) 中是否正式不尊重命名参数,或者这是我缺少的东西的副作用?如果不是,为什么不呢?

4

4 回答 4

39

实际发生了什么:

# 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"
于 2012-03-08T04:32:14.080 回答
5

我认为这里发生了两件事:

  1. 您正在为名为“范围”的方法定义一个参数,默认值为“范围”
  2. 当您调用该方法时,您将值“meh”分配给一个名为“scope”的新局部变量,它与您正在调用的方法上的参数名称无关。
于 2012-03-08T03:35:18.020 回答
3

尽管 Ruby 语言不支持命名参数,但您可以通过散列传递函数参数来模拟它们。例如:

def meth(id, parameters = {})
  options = parameters["options"] || "options"
  scope = parameters["scope"] || "scope"

  puts options
end

可以按如下方式使用:

meth(1, scope: "meh")

您现有的代码只是分配一个变量,然后将该变量传递给您的函数。有关更多信息,请参阅:http ://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html 。

于 2012-03-08T04:01:57.840 回答
0

Ruby 没有命名参数。

示例方法定义具有具有默认值的参数。

调用站点示例将值分配给名为scope的调用者范围局部变量,然后将其值(meh)传递给options参数。

于 2012-03-08T03:35:15.227 回答