Class_eval and Instance_eval

class_eval is called on a class object and is used to create instance methods for the class at runtime.

%w(administrator developer teamlead tester).each do |user|
  class_eval <<-EOR
    def is_#{user}?
      site == "MYACCOUNT_#{org.upcase}" 
    end
  EOR
end 

In the above example, whichever class the code is in, instance methods are created for that class in runtime.
Note that class_eval is called on self which is object of class Class.

instance_eval can be called on any receiver.
if the receiver is class, it creates class methods for the class.
if the receiver is instance, it creates instance methods for the class on the instance.

Sandheep About 11 years ago