簡體   English   中英

使用帶參數的instance_eval調用proc?

[英]invoking proc with instance_eval with arguments?

我知道這有效:

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

class Usa
  def hi
    "Hello!"
  end
end
Usa.new.instance_eval &proc

但是我想將參數傳遞給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

任何人都可以幫助我使它工作嗎?

需要傳遞參數時,請使用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!"

注意:它是Ruby 1.8.7的新功能,因此如果需要,升級或require 'backports'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM