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?
James already answered the question pretty well, I just want to address the "when does that line get executed?" question.
It is executed when the class is 'parsed'. For example:
irb(main):001:0> class A
irb(main):002:1> puts "Hello!"
irb(main):003:1> end
Hello!
=> nil
Notice that "Hello!" appears immediately after I define the class and it gets parsed. So the attr_writer() method (it is really just a method, not special syntax) is executed while your class is being defined and adds a method to your class for you. You can execute any ol' code you wanted within the class definition, as shown above.
Also, the attr* methods DO NOT declare any variables. They only create methods to access those variables.
irb(main):001:0> class A
irb(main):002:1> attr_reader :something
irb(main):003:1> end
=> nil
irb(main):004:0> a = A.new
=> #<A:0x40223968>
irb(main):005:0> a.instance_variables
=>
irb(main):006:0> a.methods.sort
=> ["==", "===", "=~", "__id__", "__send__", "class", "clone", "display", "dup", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "inspect", "instance_eval", "instance_of?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "methods", "nil?", "object_id", "private_methods", "protected_methods", "public_methods", "respond_to?", "send", "singleton_methods", "something", "taint", "tainted?", "to_a", "to_s", "type", "untaint"]
Notice the method called "something" which was defined by attr_reader :something.
Hope that helps.
-Justin