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 method
say_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