Ruby 块内部模块或 class

Ruby Blocks inside module or class

Ruby中的块是否可以写在class或模块中?根据文档,可以使用 yield 从方法中调用块...即它也应该可以从 classes 中的方法调用。但是对于下面的代码,我收到以下错误:

$ ruby lesson1.rb Traceback (most recent call last): 2: from lesson1.rb:1:in <main>' 1: from lesson1.rb:2:in' lesson1.rb:9:in <class:Sample>': undefined methodsay_hi' for M1::Sample:Class (NoMethodError)

文件名:lessson1.rb

module M1
  class Sample 
      def say_hi( name )
        puts "Hello, #{name}! Entered the method"
        yield
        puts "Exiting the method"
      end

      say_hi("Block") do
        puts "Good Day"
      end

    end
end

是的,您可以在 class/module 级别的方法调用中使用块。你得到错误的原因不是因为块,而是因为你在 class 的上下文中调用 say_hi,所以它正在寻找 class 本身的方法,不适用于 class 实例的方法。您将 say_hi 定义为实例方法,因此它在 class 级别不可用。如果将其更改为 def self.say_hi( name ),则可以正常工作。