From: Dan Drew Date: 2010-04-08T23:20:19+09:00 Subject: Re: Ruby newbie - Trying to understand variables ------=_NextPart_000_00BC_01CAD704.5C2351A0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable When you use attr_reader it declares a method on your class for you like = this: def isbn return @isbn end You're correct that the variable in your constructor is local to that = scope. When you call book.isbn you are actually calling the method above = which correctly returns the instance variable. Similarly if you used attr_accessor or attr_writer you would get a = setter method: def isbn=3D(val) @isbn =3D val end dan drew > brilliantsoftware.ca > shouldn't your software be brilliant?=20 From: Sask Khan=20 Sent: Thursday, April 08, 2010 9:36 AM Newsgroups: comp.lang.ruby To: ruby-talk ML=20 Subject: Ruby newbie - Trying to understand variables Hey guys, Im new to Ruby and totally new to the concept of Object Oriented Programming. At the moment, am going through Pragmatic Programmer=E2=80=99s 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 = =E2=80=98Classes, Object & Variables=E2=80=99: classBookInStock attr_reader :isbn, :price Def initialize(isbn,price) @isbn =3D isbn @price =3D Float(price) end Def price=3D(new_price) @price =3D new_price end #... End book=3DBookInStock.new("isbn1",33.80) Puts "ISBN =3D #{book.isbn}" puts"Price =3D #{book.price}" book.price =3D book.price*0.75 #discount price puts"Newprice=3D #{book.price}" Im a bit confused about the output syntax using =E2=80=98Puts=E2=80=99. = Now, I read and understand that the variable =E2=80=98@isbn=E2=80=99 is not the same as = =E2=80=98isbn=E2=80=99 variable, same for the =E2=80=98:isbn=E2=80=98 constant, all three being different = to eachother. The variable with =E2=80=98@=E2=80=99 is available outside the place = where it is defined so why are we not using the following code: Puts =E2=80=9CISNB =3D #{book.@isbn}=E2=80=9D Instead of (as per the code in the exercise above) puts =E2=80=9Cisbn=3D #{book.isbn}=E2=80=9D 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 =E2=80=98:isbn=E2=80=99 in = =E2=80=98attr_reader=E2=80=99 connected to the =E2=80=98isbn=E2=80=99 variable when we didn=E2=80=99t connect them? Any help would be most appreciated. --=20 Posted via http://www.ruby-forum.com/. ------=_NextPart_000_00BC_01CAD704.5C2351A0--