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

查看:92
本文介绍了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个小时的错误查找,我找到了这个宝石的错误,而我恰巧使用了假设命名参数将受到尊重.他们不是.

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天全站免登陆