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|
开发者_如何学JAVA 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?
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.
精彩评论