Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use implicit or explicit code blocks

Tags:

ruby

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?

like image 887
AlexH Avatar asked Sep 22 '15 14:09

AlexH


People also ask

What is an explicit block?

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 .

How code blocks are used in Ruby explain with example?

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.

Why we use blocks in Ruby?

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.

How do you pass blocks in Ruby?

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.


1 Answers

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.

like image 82
sawa Avatar answered Nov 15 '22 07:11

sawa