Прочитайте все остальные ответы для важных деталей.Но вот решение:
class MyObject
def initialize(x)
@x = x
end
def &(arg)
return [self, arg]
end
def to_s
@x
end
end
class Array
def &(arg)
if arg.is_a? MyObject
return self << arg
else
# do what Array.& would normally do
end
end
end
a = MyObject.new('a')
b = MyObject.new('b')
c = MyObject.new('c')
x = a & b & c
puts x.class
puts "[#{x.join(', ')}]"
Вот еще одно решение, которое является более безопасным (т. Е. Без обезличивания):
class MyObject
def initialize(x)
@x = x
end
def &(arg)
a = MyObjectArray.new
a << self << arg
end
def to_s
@x
end
end
class MyObjectArray < Array
def &(arg)
return self << arg
end
end
a = MyObject.new('a')
b = MyObject.new('b')
c = MyObject.new('c')
x = a & b & c
puts x.class
puts "[#{x.join(', ')}]"