So I am just starting to make my way through The Pragmatic Bookself’s, “Programming Ruby 1.9 (3rd Edition)” and I’ve come across some code that I need a little clarification on.
If you own the book, it’s in Chapter 3’s, “Classes, Objects, and Variables,” specifically in the section about virtual attributes.
Basically, a class is defined with an initializer that sets a couple of instance variables, one of which is @price. That variable has an accessor / mutator created with attr_accessor like so:
attr_accessor :price
That class also has a virtual attribute called, price_in_cents which simply returns the value from this line:
Integer(price*100 + 0.5)
Now my question is why is price in the virtual attribute not prefixed with an @? It is clearly dealing with an instance variable. Executing the code without the @ works just the same as with; why is that?
P.S. Sorry for not just posting the code wholesale—given that this is a question about code in a book, I wasn’t sure what legal right I’d have to post.
That’s a receiverless message send.
In Ruby, the receiver
selfis implicit: you can leave it out if you want to. So,priceis basically the same asself.price(ignoring access restrictions).In other words, it’s calling the method
priceyou defined withattr_accessor.