Class body is executable like in this code:
3.times do
class C
puts "hello"
end
end
What is the significance of that? I don't see the significance of class body being executable. Is it because we need the code at the top level to execute, or is it to be able to return a value? If that is not the only reason, is there a good example to show that it is a brilliant idea?
For a couple of easy examples:
It allows things like attribute accessors to work:
class Dog
attr_reader :name
end
attr_reader
and others from that family are just methods that are executed in context where self
is a class object. They are not declaractions; they actually execute as the class is being executed. It thus hinges on the ability of Ruby to call methods while defining a class.
It allows conditional definition:
class OptimisedClass
if defined? JRUBY_VERSION
def do_stuff
jruby_optimised_stuff
end
else
def stuff
c_optimised_stuff
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With