The body of the class is executable, as in this code:
3.times do class C puts "hello" end end
What is the meaning of this? I do not see the class value of the executable. Is it because we need code at the top level to execute, or can it return a value? If this is not the only reason, is there a good example to show that this is a brilliant idea?
For a few simple examples:
It allows you to work with attributes:
class Dog attr_reader :name end
attr_reader, and others from this family are just methods that execute in the context where selfis the class object. They are not declarations; they actually execute as the class executes. So it depends on the ability of Ruby to call methods when defining a class.
attr_reader
self
:
class OptimisedClass if defined? JRUBY_VERSION def do_stuff jruby_optimised_stuff end else def stuff c_optimised_stuff end end end
Ruby , . , if , . , , JRuby:
if
if RUBY_ENGINE == 'jruby' class SomeClass end end
++ Java, , , #ifdefs. Ruby " ", Ruby .
ActiveRecord - Ruby ORM, , , .