Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can &block be optional in ruby?

Tags:

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.

like image 573
TheWebs Avatar asked Mar 20 '15 16:03

TheWebs


People also ask

Can be means?

—used to say that what a person does or feels is understandable or that a person should not be blamed for doing or feeling something.

CAN is noun or verb?

can (noun) can (verb) can–do (adjective) canned (adjective) can't.

What a verb can?

The modal 'can' is a commonly used modal verb in English. It is used to express; ability, opportunity, a request, to grant permission, to show possibility or impossibility.


2 Answers

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
like image 99
Philip Hallstrom Avatar answered Nov 16 '22 02:11

Philip Hallstrom


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

like image 37
Jörg W Mittag Avatar answered Nov 16 '22 01:11

Jörg W Mittag