0
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.

Otto Allmendinger
  • 27,448
  • 7
  • 68
  • 79

3 Answers3

3

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"
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

In Ruby, assignment expressions evaluate to the value that is being assigned.

I.e.:

foo = 'bar'

evaluates to 'bar'

So, in your case

Item.new.name=("value")

which would more idiomatically be written like this:

Item.new.name = 'value'

the value being assigned is the string 'value'.

So, Item.new.name = 'value' evaluates to 'value' (with the side-effect of calling the name= method, of course), which means that

item = Item.new.name = 'value'

evaluates to

item = 'value'

And in the end, item has the value 'value', which is a String.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

on the second case you are creating a new Item and setting the name, when you set the name it returns a string, which you assign to item variable. you should use the first form

or when inherits from ActiveRecord:

item = Item.new(:name=>"value")
Lluís
  • 1,267
  • 1
  • 14
  • 36