rubyruby-block

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...i.e 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 methodsay_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

Solution

  • 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.