Search code examples
rubyobjectsetterinitializer

Ruby. Symbol '=' in to the setter name and initialization of an object


class Item

    def name=(name_value)   
        @name = name_value
    end

    def name
        @name
    end

end

In the first case:

item = Item.new
item.name=("value")
puts item.class

I keep getting.

Item

In the second case:

item = Item.new.name=("value")
puts item.class

I have

String

Why? I do not understand the difference.


Solution

  • Ruby sees your second example as this

    item = Item.new.name = 'value'
    

    Return value of an assignment operator is the value being assigned. Item.new.name = 'value' returns 'value' and so does item = 'value'.

    class Item
      def name=(name_value)
        @name = "processed #{name_value}"
      end
    
      def name
        @name
      end
    end
    
    item = Item.new
    item2 = item.name = "value" # your example code
    
    item2 # => "value"
    item.name # => "processed value"