From: Paul Smith Date: 2010-04-08T23:15:00+09:00 Subject: Re: Ruby newbie - Trying to understand variables With the class BookInStock you must refer to the instance variable isbn with the @ in front to show that it is an instance variable. Within a BookInStock method for example, @isbn refers to the isbn instance variable owned by the instance that method was called on. Outside of the class definition, you have created an instance of BookInStock and called that instance book. There, book.isbn refers to the method called isbn that's defined on BookInStock. Finally, attr_reader is a method which takes :isbn (the symbol) as a parameter, and generates the necessary 'getter' method to access the @isbn instance variable from outside the class definition. This is what wires up book.isbn to @isbn in the class definition. attr_reader :isbn is the same as def isbn @isbn end Hope that helps! Paul Smith paul@pollyandpaul.co.uk On Thu, Apr 8, 2010 at 2:36 PM, Sask Khan wrote: > Hey guys, > > Im new to Ruby and totally new to the concept of Object Oriented > Programming. > > At the moment, am going through Pragmatic Programmer’s Ruby and even > though am finding it to awesome, I have a few questions > > Below is the exercise we are going through in the chapter ‘Classes, > Object & Variables’: > > classBookInStock > attr_reader :isbn, :price > Def initialize(isbn,price) > @isbn = isbn > @price = Float(price) > end > Def price=(new_price) > @price = new_price > end > #... > End > book=BookInStock.new("isbn1",33.80) > Puts "ISBN = #{book.isbn}" > puts"Price = #{book.price}" > book.price = book.price*0.75       #discount price > puts"Newprice= #{book.price}" > > Im a bit confused about the output syntax using ‘Puts’. Now, I read and > understand that the variable ‘@isbn’ is not the same as ‘isbn’ variable, > same for the ‘:isbn‘ constant, all three being different to eachother. > The variable with ‘@’ is available outside the place where it is defined > so why are we not using the following code: > > Puts “ISNB = #{book.@isbn}” > > Instead of  (as per the code in the exercise above) > > puts “isbn= #{book.isbn}” > > The reason I think we should be using the variable with @ is because the > one without @ is not accessible outside where it is defined, right? And > as the two variables (@isbn, isbn) are different to each other. Also, > how is the constant ‘:isbn’ in ‘attr_reader’ connected to the ‘isbn’ > variable when we didn’t connect them? > > > > > Any help would be most appreciated. > -- > Posted via http://www.ruby-forum.com/. > >