使对象的行为类似于 Ruby 中的并行分配数组 [英] make an object behave like an Array for parallel assignment in ruby

查看:25
本文介绍了使对象的行为类似于 Ruby 中的并行分配数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在 Ruby 中执行此操作:

ar = [1, 2]x, y = ar

那么,x == 1 和 y == 2.有没有我可以在我自己的类中定义的方法会产生相同的效果?例如

rb = AllYourCode.newx, y = rb

到目前为止,对于这样的赋值,我所能做的就是使 x == rb 和 y = nil.Python 有一个这样的特性:

<预><代码>>>>Foo类:...定义 __iter__(self):...返回迭代器([1,2])...>>>x, y = Foo()>>>X1>>>是2

解决方案

是的.定义#to_ary.这将使您的对象被视为要赋值的数组.

irb>o = Object.new=>#<对象:0x3556ec>irb>def o.to_ary[1, 2]结尾=>零irb>x, y = o=>[1,2]irb>X#=>1irb>是#=>2

#to_a#to_ary 的区别在于 #to_a 用于尝试转换一个给定的对象到一个数组,而 #to_ary 是可用的,如果我们可以把给定的对象当作一个数组.这是一个微妙的区别.

Suppose you do this in Ruby:

ar = [1, 2]
x, y = ar

Then, x == 1 and y == 2. Is there a method I can define in my own classes that will produce the same effect? e.g.

rb = AllYourCode.new
x, y = rb

So far, all I've been able to do with an assignment like this is to make x == rb and y = nil. Python has a feature like this:

>>> class Foo:
...     def __iter__(self):
...             return iter([1,2])
...
>>> x, y = Foo()
>>> x
1
>>> y
2

解决方案

Yep. Define #to_ary. This will let your object be treated as an array for assignment.

irb> o = Object.new
=> #<Object:0x3556ec>
irb> def o.to_ary
       [1, 2]
     end
=> nil
irb> x, y = o
=> [1,2]
irb> x
#=> 1
irb> y
#=> 2

The difference between #to_a and #to_ary is that #to_a is used to try to convert a given object to an array, while #to_ary is available if we can treat the given object as an array. It's a subtle difference.

这篇关于使对象的行为类似于 Ruby 中的并行分配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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