使用带参数的instance_eval调用proc?

Nic*_*ilt 33 ruby

我知道这有效:

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

class Usa
  def hi
    "Hello!"
  end
end
Usa.new.instance_eval &proc
Run Code Online (Sandbox Code Playgroud)

但是我想将参数传递给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
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮助我使它工作吗?

Mar*_*une 61

使用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!"
Run Code Online (Sandbox Code Playgroud)

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

  • 有什么`backports`*不能*吗?:-) (2认同)