如何在块中调用 Class 方法?

How to call Class methods in block?

class ShoppingList
  def add(a,b)
    print a,b
  end
  def items(&block)
    block.call
  end
end

s1 = ShoppingList.new
s1.add(4,10)
s1.items do 
  add(5,2)
end

main:Object

的未定义方法“添加”

(repl):19:在`块中'

(repl):12:在“项目”中

如何在块中调用add?..

如果您想在 items 消息收件人的上下文中调用 block,您可以使用 instance_eval:

def items(&block)
  instance_eval(&block)
end