Ruby 中没有命名参数? [英] No named parameters in Ruby?

查看:18
本文介绍了Ruby 中没有命名参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is so simple that I can't believe it caught me.

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

meth(1, scope = "meh")

-> "meh"

我倾向于使用散列作为参数选项,因为这是群体所做的——而且非常干净.我以为这是标准.今天,经过大约 3 个小时的 bug 搜索,我将错误追溯到我碰巧使用的这个 gem,假设 命名参数将受到尊重.他们不是.

I tend to use hashes for argument options just because it was how the herd did it– and it is quite clean. I thought it was the standard. Today, after about 3 hours of bug hunting, I traced down an error to this gem I happen to be using that assumes named parameters will be honored. They are not.

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

推荐答案

实际发生的事情:

# 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 的结果作为 meth 中的 options 值传递代码>.当然,该赋值的值是 "meh".

There is no support* for named parameters (see below for 2.0 update). What you're seeing is just the result of assigning "meh" to scope being passed as the options value in meth. The value of that assignment, of course, is "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"

等等.不过,由于缺少命名参数,它们都是解决方法.

And so on. They're all workarounds, though, for the lack of named parameters.

* 好吧,至少在即将到来的 Ruby 2.0 之前,支持关键字参数!在撰写本文时,它位于候选版本 2 上,这是正式发布之前的最后一个.虽然您需要了解上述方法才能使用 1.8.7、1.9.3 等,但那些能够使用较新版本的人现在可以选择以下选项:

* Well, at least until the upcoming Ruby 2.0, which supports keyword arguments! As of this writing it's on release candidate 2, the last before the official release. Although you'll need to know the methods above to work with 1.8.7, 1.9.3, etc., those able to work with newer versions now have the following option:

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

meth 1, scope: "meh"
# => "options"

这篇关于Ruby 中没有命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆