简体   繁体   中英

Ruby Blocks inside module or class

Can a block in Ruby be written inside class or module? as per docs a block can be called from methods using yield...ie it should be callable from methods in classes also. 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)

File Name: 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. You defined say_hi as an instance method, so it's unavailable at the class level. If you change it to def self.say_hi( name ) , it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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