TheWebs
TheWebs

Reputation: 12923

can &block be optional in ruby?

Is this possible? For example if I have:

module Sample
  def self.method_name(var, &block)
    if var == 6
      call_other_method(var, &block)
    else
      call_other_method(var)
    end
  end

  def self.call_other_method(var, &block)
    # do something with var and block, assuming block is passed to us.
  end
end

So in the above example, if you call the Sample.method_name and pas it a 3 and a block, that block would not be used because the input doesn't match the conditional. But is this possible? Can you make a &block optional?

I made the assumption, based on other stack questions that you can pass a &block from one method to the next as shown above, if this is wrong please fill me in.

Upvotes: 11

Views: 5675

Answers (2)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Sure. Check out block_given? in the ruby docs.

http://ruby-doc.org/core-2.2.1/Kernel.html#method-i-block_given-3F

module Sample
  def self.method_name(var, &block)
    if var == 6
      call_other_method(var, &block)
    else
      call_other_method(var)
    end
  end

  def self.call_other_method(var, &block)
    puts "calling other method with var = #{var}"
    block.call if block_given?
    puts "finished other method with var = #{var}"
  end
end

When run the output is:

calling other method with var = 6
this is my block
finished other method with var = 6
calling other method with var = 3
finished other method with var = 3

Upvotes: 19

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

Yes, it is possible. In fact, the code you posted already works just fine as-is.

Upvotes: 2

Related Questions