35

I know this works:

proc = Proc.new do
  puts self.hi + ' world'
end

class Usa
  def hi
    "Hello!"
  end
end
Usa.new.instance_eval &proc

However I want to pass arguments to proc, so I tried this which does not work:

proc = Proc.new do |greeting| 
  puts self.hi + greeting
end

class Usa
  def hi
    "Hello!"
  end
end
Usa.new.instance_eval &proc, 'world' # does not work
Usa.new.instance_eval &proc('world') # does not work

Can anyone help me make it work?

2
  • You have a typo. gsub!("gretting", "greeting") May 3, 2010 at 15:45
  • fixed now. Sorry about that. Thanks Marc. May 3, 2010 at 15:51

1 Answer 1

66

Use instance_exec instead of instance_eval when you need to pass arguments.

proc = Proc.new do |greeting| 
  puts self.hi + greeting
end

class Usa
  def hi
    "Hello, "
  end
end
Usa.new.instance_exec 'world!', &proc # => "Hello, world!"

Note: it's new to Ruby 1.8.7, so upgrade or require 'backports' if needed.

2
  • 2
    Is there anything backports can't do? :-) May 3, 2010 at 16:00
  • @Jörg :-) I wish there wasn't... Too bad some things are out of reach, like Method#source_location or the encoding stuff. And instance_exec is the ugliest hack in the gem... May 3, 2010 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.