Instance_eva()l-ing a proc with parameters

Dear friends,

I need to evaluate a proc within an instance context and would like to
pass it a parameter. The only straight forward way I found is to use
instance_eval(), however it does not allow to pass parameters to a proc,
only the instance itself is passed as a single parameter:

[rh-30-x86.irvspxl08:1004]gbystrit> irb
irb(main):001:0> [ VERSION, PLATFORM ]
=> [“1.8.4”, “i686-linux”]
irb(main):002:0> block = proc { |*_args| puts _args.inspect }
=> #Proc:[email protected]:2(irb)
irb(main):003:0> class A; end
=> nil
irb(main):004:0> a = A.new
=> #<A:0xb75a9674>
irb(main):005:0> a.instance_eval &block
[#<A:0xb75a9674>]
=> nil
irb(main):006:0> a.instance_eval 1, 2, &block # Hypothetical
ArgumentError: wrong number of arguments (2 for 0)
from (irb):6:in `instance_eval’
from (irb):6
from :0

Is there any easy way to do what I want? I also found that I can use
define_method() to turn a proc into an instance method and then call it
with parameters, however it involves a lot of hassle (for one,
define_method() is private).

Any thoughts?

Thank you,
Gennady B…

On Tue, Oct 03, 2006 at 01:35:48AM +0900, Gennady B. wrote:

Dear friends,

I need to evaluate a proc within an instance context and would like to
pass it a parameter. The only straight forward way I found is to use
instance_eval(), however it does not allow to pass parameters to a proc,
only the instance itself is passed as a single parameter:
Google for instance_exec, there are various and sundry implementations,
including one built into rails.

http://eigenclass.org/hiki.rb?instance_exec has various implementations
and their respective strengths and weaknesses. Or you can just use ruby
1.9 where it’s part of the core.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs