开发者

invoking proc with instance_eval with arguments?

开发者 https://www.devze.com 2022-12-29 04:07 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消