I'm trying to understand when one should code blocks implicitly or explicitly. Given the following code blocks:
Implicit
def two_times_implicit
return "No block" unless block_given?
yield
yield
end
puts two_times_implicit { print "Hello "}
puts two_times_implicit
Explicit
def two_times_explicit (&i_am_a_block)
return "No block" if i_am_a_block.nil?
i_am_a_block.call
i_am_a_block.call
end
puts two_times_explicit { puts "Hello"}
puts two_times_explicit
Is it preferable to code using one over the other? Is there a standard practice and are there instances where one would work better or differently than the other and where one would not work at all?
The explicit statement block defines a different variable named distance and gives it a value of 2 . However, the RETURN statement returns the value stored in the first distance variable, or 37 .
The code in the block is always enclosed within braces ({}). A block is always invoked from a function with the same name as that of the block. This means that if you have a block with the name test, then you use the function test to invoke this block. You invoke a block by using the yield statement.
Since Ruby blocks can access variables declared outside the block body, our total method is able to use each with a block to update the amount variable. The amount variable is set to 0 , and then each is called on the array. Each of the values in the array is passed to the block.
In Ruby, methods can take blocks implicitly and explicitly. Implicit block passing works by calling the yield keyword in a method. The yield keyword is special. It finds and calls a passed block, so you don't have to add the block to the list of arguments the method accepts.
Receiving a block via &
creates a new proc object out of the block, so from the point of view of efficiency, it is better not to use it. However, using &
generally makes it easier to define methods that may or may not take a block, and using &
, you can also handle blocks together with arguments, so it is preferred by many.
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