tags:

views:

35

answers:

1

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. Can anyone help me make following 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
+3  A: 

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.

Marc-André Lafortune
Is there anything `backports` *can't* do? :-)
Jörg W Mittag
@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...
Marc-André Lafortune