Peer A. wrote:
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