Ruby - 方法内的块作用域

Ruby - Block scope inside method

我创造了一些class

class Book
  def perform
    yield
  end
end

然后我想调用将调用 method1method2 的块。然而,这两种方法都没有定义,我不想定义它们。而不是这个我想打电话给 method_missing 但我得到: undefined local variable or method 'method1' for main:Object (NameError)

book = Book.new
book.perform do
  method1
  method2
end

那我该怎么办?

为了完成您的要求,我相信您需要像这样重新定义 method_missing

class Book
  def perform
    yield
  end
end

def method_missing(methodname, *args)
  puts "#{methodname} called"
end

book = Book.new
book.perform do
  method1
  method2
end

#=>
#method1 called
#method2 called