--- Martin <yodlep / gmail.com> wrote:

> Hi,
> 
> I'm having trouble with Procs.
> 
> The following piece of code works only if I use "x.green"
> rather than just
> plain "green"
> 
> class Foo
>   def red(&p)
>     @z = p
>   end
> 
>   def blue(y)
>     instance_eval{@z.call y}
>   end
> 
>   def green
>     puts "Yeah!"
>   end
> end
> 
> x = Foo.new
> 
> x.red do |y|
>   green # I don't want to use x.green
>   puts y
> end
> 
> x.blue 5
> The following code works. It is able to call the "green"
> method from inside
> the Foo class without being able to prefix it with "x.", but
> I can't handle
> any arguments like in the above code:
> 
> class Foo
>   def red(&p)
>     @z = p
>   end
> 
>   def blue
>     instance_eval(&@z)
>   end
> 
>   def green
>     puts "Yeah!"
>   end
> end
> 
> x = Foo.new
> 
> x.red do
>   green
> end
> 
> x.blue
> 
> My main goal is to be able to refer to the "green" in the
> closure "x.red do
> green end" without using "x.green" and also be able handle
> arguments at the
> same time like in the first piece of code, but as you know,
> the first piece
> of code doesn't work.
> 
> 
> Is there any way to achieve this?

I don't think so.  I think there was a thread about adding an
argument passing instance_eval type method and matz was asking
for suggestions of method names.

What's so bad about using a receiver for Foo#green?  Using
instance_eval can be dangerous because you bypass all
protections/encapsulation.  It also can get confusing because
the block only has access to local variables in the defining
context and not methods, instance variables, etc like other
blocks have access to.

Personally, I think it is better to pass in self as an argument
rather than use instance_eval so casually.  I usually use
instance_eval only when I have to - to bypass proctections.



	
		
__________________________________ 
Yahoo! Mail - PC Magazine Editors' Choice 2005 
http://mail.yahoo.com