Ruby 可链接方法/数组
如何实现“<<”用作可链接方法时具有相同的行为吗?
class Test
attr_accessor :internal_array
def initialize
@internal_array = []
end
def <<(item)
@internal_array << :a
@internal_array << item
end
end
t = Test.new
t << 1
t << 2
t << 3
#t.internal_array => [:a, 1, :a, 2, :a, 3]
puts "#{t.internal_array}" # => a1a2a3
t = Test.new
t << 1 << 2 << 3
#t.internal_array => [:a, 1, 2, 3]
puts "#{t.internal_array}" # => a123 , Why not a1a2a3?
我希望这两种情况给出相同的结果。
How do I implement the '<<' to have the same behavior when used as a chainable method?
class Test
attr_accessor :internal_array
def initialize
@internal_array = []
end
def <<(item)
@internal_array << :a
@internal_array << item
end
end
t = Test.new
t << 1
t << 2
t << 3
#t.internal_array => [:a, 1, :a, 2, :a, 3]
puts "#{t.internal_array}" # => a1a2a3
t = Test.new
t << 1 << 2 << 3
#t.internal_array => [:a, 1, 2, 3]
puts "#{t.internal_array}" # => a123 , Why not a1a2a3?
I want both cases giving the same result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加
self
作为 << 中的最后一行方法来返回它。事实上,您隐式返回数组,而不是实例。Add
self
as the last line in the << method to return it. As is, you're implicitly returning the array, not the instance.上面答案的解释:
当一个方法被链接时,下一个方法将应用于第一个方法的结果。
例如:
下面的代码可以工作
,但 this 不会,
因为类 B 的实例(A.new.method1 的结果)没有实现 method3。这与以下内容相同:
上面问题中使用的代码有一点技巧,因为 Test 和 Array 都有方法 <<。但我想要测试#<<返回 self,而不是返回的 @internal_array。
Explanation of the answer above:
When a method is chained, the next method is applied to the result of the first method.
For exemplo:
The code below will work
but the this will not
because an instance of class B, which is the result of A.new.method1 doesn't implement method3. This is the same of:
The code used in the question above, was a little bit more trick, because both, Test and Array had the method <<. But I want Test#<< to return self, and not the @internal_array that was being returned.