Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoking proc with instance_eval with arguments?

Tags:

ruby

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?

like image 518
Nick Vanderbilt Avatar asked May 03 '10 15:05

Nick Vanderbilt


1 Answers

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.

like image 86
Marc-André Lafortune Avatar answered Oct 23 '22 06:10

Marc-André Lafortune