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.
—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 (noun) can (verb) can–do (adjective) canned (adjective) can't.
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.
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
Yes, it is possible. In fact, the code you posted already works just fine as-is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With