微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ruby – 重写/启用多个赋值(例如`a,b,c = d,e,f`)

在ruby,你可以这样做:
d = [1,2,3]
a,b,c = d

a,b和c将分别接收值1,2和3.

d,在这种情况下,在Array中,ruby知道将其内容分配给a,b和c.但是,如果d是一个Fixnum,例如,只有一个将分配给d的值,而b和c将被分配为nil.

d的什么属性允许它用于多个赋值?在我到目前为止的探索中,我只能以这种方式使Array的子​​类的实例行为.

解决方法

这是一个非常无证的功能,我谨慎使用,但我们走了.从书中的Ruby编程语言:

When there are multiple lvalues and
only a single rvalue,Ruby attempts to
expand the rvalue into a list of
values to assign. If the value is an
array,Ruby expands the array so that
each element becomes its own rvalue.
If the value is not an array but
implements a to_ary method,Ruby
invokes that method and then expands
the array it returns.

在Ruby 1.8中,这是to_ary方法,在Ruby 1.9文档中说它调用to_splat,但是我没有测试(在这台机器中没有1.9)它没有按预期的方式工作.所以,你必须在对象中定义一个to_ary方法.

class Week
  def to_ary
    %w(monday tuesday wednesday thursday friday saturday sunday)
  end
end

mon,tue,wed,thu,*weekend = Week.new

*%w(…)对于一系列单词是一个特殊的符号,如果你懒惰写[‘星期一’,’星期二’…]

原文地址:https://www.jb51.cc/ruby/271031.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐