简体   繁体   English

模块或类中的Ruby块

[英]Ruby Blocks inside module or class

Can a block in Ruby be written inside class or module? Ruby中的块可以写在类或模块内部吗? as per docs a block can be called from methods using yield...ie it should be callable from methods in classes also. 根据文档,可以使用yield的方法调用一个块...即它也应该可以从类中的方法调用。 But for the below code as I am getting the following error: 但是对于下面的代码,我得到以下错误:

$ 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 method say_hi' for M1::Sample:Class (NoMethodError) $ ruby​​ lesson1.rb追溯(最近一次通话最近):2:从lesson1.rb:1:in <main>' 1: from lesson1.rb:2:in in'lesson1.rb:9:in <class:Sample>': undefined method M1 :: Sample:Class的<class:Sample>': undefined method say_hi'(NoMethodError)

File Name: lessson1.rb 文件名: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

Yes, you can use a block in a method call at the class/module level. 是的,您可以在类/模块级别的方法调用中使用块。 The reason you're getting the error isn't because of the block but because you're calling say_hi in the context of the class, so it's looking for methods of the class itself, not for methods of instances of the class. 出现错误的原因不是由于块,而是因为您在类的上下文中调用say_hi ,因此它正在查找类本身的方法,而不是类的实例的方法。 You defined say_hi as an instance method, so it's unavailable at the class level. 您将say_hi定义为实例方法,因此在类级别上不可用。 If you change it to def self.say_hi( name ) , it works fine. 如果将其更改为def self.say_hi( name ) ,它将正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM