1

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

$ ruby​​ course1.rb Traceback(最近一次调用最后一次):2:来自 course1.rb:1:in <main>' 1: from lesson1.rb:2:in' course1.rb:9:in <class:Sample>': undefined methodsay_hi' for M1::Sample:Class (NoMethodError)

文件名:lesson1.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
4

1 回答 1

2

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

于 2018-09-09T02:42:38.413 回答