On May 10, 4:21 pm, MenTaLguY <men... / rydia.net> wrote:
> On Fri, 11 May 2007 07:06:29 +0900, Vasco Andrade e silva <vasc... / gmail.com> wrote:
>
> > By the way are class_eval, module_eval, instance_eval and instance_exec
> > the only exceptions?
>
> In Ruby's core library, yes.  It's possible to implement new methods with similar behavior
> (which is occasionally useful), but that isn't the norm.

For example:

class Person
  attr_accessor :name, :age
  def initialize( name )
    @name = name
    @age  = 0
  end
  def grow_older
    @age += 1
  end
end

def create( name, &block )
  person = Person.new( name )
  person.instance_eval( &block )
  p person
end

create( :gavin ){
  @age = 32
  grow_older
}
#=> #<Person:0x28347c4 @age=33, @name=:gavin>



Using instance eval makes some DSLs (domain specific languages) easier
to create, rather than having to use the object yielded to the block
in every call. Compare the usage of 'create' above to this usage:

def create( name )
  person = Person.new( name )
  yield person
  p person
end

create( :gavin ){ |person|
  person.age = 32
  person.grow_older
}
#=> #<Person:0x28347c4 @age=33, @name=:gavin>