给出以下代码:
class MagicList
def items=(array)
@items = array.map{|x| x*2}
end
def items
@items
end
end
list = MagicList.new
returns = list.items=([1, 2, 3])
puts returns.inspect # => [1, 2, 3]
puts list.items.inspect # => [2, 4, 6]
我预计returns
的值为[2, 4, 6]
,因为@items
和array.map{|x| x*2}
都会返回此值。为什么是[1, 2, 3]
?
答案 0 :(得分:9)
因为Ruby赋值总是返回它们传递的项,无论setter=
方法返回什么。
另见Is it possible to have class.property = x return something other than x?