Hi --

On Thu, 17 May 2007, Vasco Andrade e Silva wrote:

> MenTaLguY wrote:
>> 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.
>>
>> -mental
>
> How can i do that?
>
> I was thinking.. If I want to "bind" self to yield context, with 0
> params, i can use a solution like this one:
>
>> def create( name, &block )
>>  person = Person.new( name )
>>  person.instance_eval( &block )
>>  p person
>> end
>
> person.instance_eval( &block ) # some kind of yield(self) inside
> instance_eval
>
> but what if i want yield with params, and still have self like
> instance_eval?
>
> Example:
> class A
>  def some_method(&block)
>    yield(:arg1, :arg2)
>  end
> end
> a = A.new
> # wanted: self "equals" to a
> a.some_method { |arg1, arg2| p self }

That's actually what instance_exec does:

# Requires Ruby 1.9
class A
   def x(&block)
     instance_exec(1,2,&block)
   end
end

A.new.x {|a,b| p a, b, self }

# Output
   1
   2
   #<A:0xb7f00700>

I still don't know what the rationale is for the name, or how one is
supposed to know that instance_exec does it this way and instance_eval
does it the other way (except that I've been using instance_eval for
longer, but that won't help people who are just starting to learn
Ruby).


David

-- 
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
    (See what readers are saying!  http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)