RT,Setter 方法返回值为传入参数。很惭愧直到今天才知道。
代码示例
class User
attr_reader :name
def name=(name)
@name = name
self
end
end
original_array = ["aaa", "bbb", "bbb"]
result = original_array.collect { |str| User.new.name = str }
puts result.inspect # => ["aaa", "bbb", "bbb"]
正确写法是
original_array.collect { |str| User.new.tap { |user| user.name = str } }