a1a2a3 t = Test.new t [:a, 1, 2, 3] put-6ren">
gpt4 book ai didi

Ruby 链式方法/数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:57:55 25 4
gpt4 key购买 nike

如何实现“<<”以在用作可链接方法时具有相同的行为?

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?

我希望两种情况都给出相同的结果。

最佳答案

self 添加到 << 方法的最后一行以返回它。照原样,您将隐式返回数组,而不是实例。

关于Ruby 链式方法/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3375104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com