From: James Britt Date: 2006-06-10T13:07:30+09:00 Subject: Re: Ruby Class question Peer Allan wrote: > Hi all, > > I am really starting to get into ruby and I am currently reading the > PickAxe book and the Agile Rails book, but there is one part of classes > that I don't understand and I can't seem to find any reference to it. > > Here is a basic class as defined in the Pickaxe book: > > 1: class Song > 2: attr_writer :duration > 3: end > > My question is, what is the whole statement on line #2? I know what it > does, it creates a attribute-setting method for the "duration" variable, > but what I don't understand is how it does it. When does that line of > code get executed? > > I am used to doing classes in C++ and PHP where the only thing outside > methods and inside a class are class variable declarations. Is this a > way to make variable declarations with a method? > > This seems to be a very common construct in Ruby and I want to > understand what it is and how to use it correctly. Thanks In Ruby, objects interact with other objects my sending messages. Messages usually (but not always) map to methods; methods in turn can manipulate instance variables. Instance variables (the @foo things) are private, but if you want to create the appearance that an object has public properties, you can create methods that match the instance variables: def foo @foo end def foo=( val ) @foo=val end This is such a common convention that Ruby has a method that writes these methods for you: attr_accessor :foo This take symbol :foo and uses it to create the pair of methods that reference an instance variable of the same name. Note that you can always create such methods by hand, and the names need not match the internal variables; such properties are just methods calls: # Create the appearance of a "public property" called 'foo' def foo @bar end def foo=( val ) @bar=val end And you can add whatever code you like to these methods. A few things to note: Ruby methods usually return the value of the last expression evaluated, but methods that end with '=' do not follow this; they return the value passed to the method. When you use attr_accessor, attr_reader, or attr_writer to create these methods, RDoc will list them as *attributes*, not as methods; they will not appear in the list of methods in the class's RDoc. (If you create the exact same methods by hand, though, RDoc treats them as methods.) -- James Britt http://www.ruby-doc.org - Ruby Help & Documentation http://www.artima.com/rubycs/ - The Journal By & For Rubyists http://www.rubystuff.com - The Ruby Store for Ruby Stuff http://www.jamesbritt.com - Playing with Better Toys http://www.30secondrule.com - Building Better Tools