使用带参数的instance_eval调用proc?

时间:2010-05-03 15:39:09

标签: ruby

我知道这有效:

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

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

但是我想将参数传递给proc,所以我试过这个不起作用:

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

任何人都可以帮助我让它发挥作用吗?

1 个答案:

答案 0 :(得分:58)

当您需要传递参数时,请使用instance_exec代替instance_eval

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!"

注意:它是Ruby 1.8.7的新功能,所以如果需要升级或require 'backports'

相关问题