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 = 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?
任何人都可以帮助我使它工作吗?
1 个解决方案
#1
54
Use instance_exec
instead of instance_eval
when you need to pass arguments.
需要传递参数时,请使用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!"
Note: it's new to Ruby 1.8.7, so upgrade or require 'backports'
if needed.
注意:它是Ruby 1.8.7的新功能,因此如果需要,升级或需要“backports”。
#1
54
Use instance_exec
instead of instance_eval
when you need to pass arguments.
需要传递参数时,请使用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!"
Note: it's new to Ruby 1.8.7, so upgrade or require 'backports'
if needed.
注意:它是Ruby 1.8.7的新功能,因此如果需要,升级或需要“backports”。