Bruce F. wrote in post #959861:
I’m a newcomer to Ruby, and I’m confused about what executable
statements which are in a class definition, but not explicitly in a
method, mean. How are they executed? I assume that there’s an implicit
method that they define; is that right?
No.
When you load a ruby script, firstly it is parsed into an internal
representation, and then that representation is stepped through and
executed.
Even the definition of a class, and the creation of methods, is done
dynamically at runtime. For example:
a = gets.chomp
b = gets.chomp
if a == b
class Foo
end
else
class Bar
end
end
In this program, if you enter two strings the same then a class Foo is
created (but not Bar); if they are different, then Bar is created (but
not Foo).
Most of the time, class definitions are not inside any conditional, but
they are still dynamic. This means they don’t exist until the class
definition code has run.
a = Foo.new # runtime error: Foo does not exist
class Foo
end
b = Foo.new # this is OK
Now, consider that ‘def’ is also a runtime action, which when it
executes, defines (or redefines) a method. The same issue applies:
wibble(123) # runtime error: No such method
def wibble(a)
puts a
end
wibble(456) # this is OK
Put the two together, and class … def … end … end is just code
which is executed. class Foo only does two things: it creates Foo if it
doesn’t already exist, and it sets the class context to which any
enclosed ‘def’ statements apply.
So now consider this:
puts “Hello world!” # this is executed before Foo created
class Foo
puts “About to define bar” # Foo created, bar hasn’t yet
def bar
puts “Yay!”
end
puts “Finished defining bar”
end
Foo.new.bar
Can you work out what this will print when you run it? When you’ve had a
think, run it to check.
HTH,
Brian.