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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With