1

Given the following code:

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]

I expected the value of returns to be [2, 4, 6], because @items as well as array.map{|x| x*2} both return this value. Why is it [1, 2, 3]?

4
  • 1
    Because Array#map doesn't change the original variable; Array#map! changes the original variable. Commented Jul 13, 2012 at 13:33
  • But I do not return the default variable. Even when I add return @items to def items= it still returns the original array. Commented Jul 13, 2012 at 13:35
  • @iblue Setters always return the right hand side of the assignment. Commented Jul 13, 2012 at 13:36
  • @RobertK It's still the last expression in the method and thus would be returned if the method weren't a setter. Commented Jul 13, 2012 at 13:36

1 Answer 1

8

Because Ruby assignments always return the item they were passed, regardless of what the setter= method returns.

See also Is it possible to have class.property = x return something other than x?

Sign up to request clarification or add additional context in comments.

6 Comments

Oh. I didn't know that. Where is this documented?
@Gareth to be specific, the items= method does return [2,4,6], it's the assignment that is working differently when a = is involved.
@Stefan I'm not sure where you get that impression from. returns = (list.items = [1, 2, 3]) would show that the return value of the setter is the same as the argument that's passed in. If [2, 4, 6] was being returned then how could the returns variable be set to anything else?
@Gareth: list.send(:items=, [1, 2, 3]) returns [2, 4, 6]
@Gareth Ruby sets the variable to the right-most value because of the chained assignment. Try returns = list.send(:items=,[1,2,3])
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.