small medium large xlarge

23 Jun 2010, 02:29
Malcolm Arnold (21 posts)

Pg 63 has the following code:

class Greeter
def initialize(name)
@name = name
Report erratum
this copy is (B4.0 printing, May 26, 2010) Prepared exclusively for Robert M Arnold
def name
def name=(new_name)
@name = new_name
g ="Barney" )
puts #=> Barney = "Betty"
puts #=> Betty 


Shouldn’t the 2nd to last line of code be: "Betty" 


With no space between name and = as indicates a method call? Whereas, the way it is written indicates an assignment of value?

If I am wrong Sam, pardon me as I just learning Ruby(read half way through 2 Ruby books before starting this one).

23 Jun 2010, 03:26
John H Simmonds (13 posts)

I’m also a starter Rubyist but I grabbed a copy of Programming Ruby 1.9 .. right there on p133 is a Section on Assignment. The code line you’ve mentioned doesn’t care about the space because you’ve got an Object reference in the lvalue, so Ruby invokes the @name=@ method on the @Greeter@ instance. (this is the second form of assignment)

23 Jun 2010, 04:18
Malcolm Arnold (21 posts)

Thanks John,

For providing the page number so I could look up the reference in Programming Ruby 1.9. I had forgotten this syntatic sugar. I didn’t understand the explanation there as well as I did on pages 69,70 of the Well Grounded Rubyist. This may be due to the fact that I haven’t read through Programming Ruby 1.9 to get the specific explanation on page 134. From what I gather on page 134, this is a change in versions >= Ruby 1.8.

Thanks again.

23 Jun 2010, 05:45
Seth Arnold (21 posts)

At least 1.8 behaved the same way:

$ irb1.8
irb(main):001:0> class Foo
irb(main):002:1> attr_accessor :name
irb(main):003:1> end
=> nil
irb(main):004:0> f =
=> #<Foo:0x7fb08a218ff8>
irb(main):005:0> = "hello"
=> "hello"
=> "hello"
23 Jun 2010, 14:20
Malcolm Arnold (21 posts)

From what I understood(if correctly) on page 134 of Programming Ruby, this was for anything < Ruby 1.8 (i.e. 1.7 and below). There is an example on 134 that shows how it would be interpreted in 1.7(and below) and how starting in 1.8.

You must be logged in to comment