Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the significance of class body being executable?

Tags:

ruby

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?

like image 249
meizin Avatar asked Mar 17 '23 10:03

meizin


1 Answers

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
like image 76
Amadan Avatar answered Apr 02 '23 08:04

Amadan