Ruby中Array#map的隐式返回值

时间:2012-07-13 13:31:31

标签: ruby

给出以下代码:

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],因为@itemsarray.map{|x| x*2}都会返回此值。为什么是[1, 2, 3]

1 个答案:

答案 0 :(得分:9)

因为Ruby赋值总是返回它们传递的项,无论setter=方法返回什么。

另见Is it possible to have class.property = x return something other than x?