rubyruby-block

Ruby: passing blocks as parameters from oustide class


I am getting below error when executing code:

example.rb:9:in `<main>': undefined method `each' for main:Object (NoMethodError)

Line 9 is second last line in my code.

My code:

class TargetProvider
  def each(target,&block)
    block.call(target)
  end   
end

tp = TargetProvider.new
each { puts "Hello!" }
tp.each(1, each)

My motive is to call block with target parameter.

How can I pass a block outside class. Any help please.


Solution

  • Here is yout code:

    class TargetProvider
      def each(target,&block)
        block.call(target)
      end   
    end
    
    tp = TargetProvider.new
    each { puts "Hello!" } # this line is trying to run a method called each
    tp.each(1, each)
    

    You need to define a lambda or a proc and store it in a variable, or use the implicit block of the each. Here is an example using a lambda:

    class TargetProvider
      def each(target,&block)
        block.call(target)
      end   
    end
    
    tp = TargetProvider.new
    each_block = lambda { |a| puts "Hello!" }
    tp.each(1, &each_block)
    

    Here is an example using the implicit block:

    class TargetProvider
      def each(target,&block)
        block.call(target)
      end   
    end
    
    tp = TargetProvider.new
    each_block = lambda { |a| puts "Hello!" }
    tp.each(1) { puts "Hello!" }