0

Code Block in Ruby

Last month, while I am working, I found that I am overlook on ruby code block. Than I myself getting confuse on how this thing work. And it take me some time to research and understand the truely power of ruby code block.

Code block is the great feature which provided by ruby language, but most people include me always overlook on this feature. Today, I am going to share my understanding about the awesome feature of code block which provide by ruby, but what is block?

What is block?

For some programming language a block is basically just code that you put inside {} or do and end. But ruby is more than that, you can do some margic staff inside the ruby block which other language cannot.

In ruby we can write block in two ways:

  • Inline: we just put our between { and }.

    Example:

   [1,2,3,4].each{ |number| puts number}
  • Multi-line: we just put our between do and end.

    Example:

  ["Rathanak", "Love", "Framgia"].each do |str|
      puts str
  end

The awesomeness of yield

yield is the ingredient for confusing us when we learn ruby code block. However, it is also the ingredient for us to do some magic on our code block. So how yield work?

When the execution on method_name reaches the line with the call to yield, the code inside the block gets executed. Then, when the code inside the block finishes, the execution of method_name continues.

Example:

  # declare method which have yield inside
  def example_method
      puts "- This is on top of yield"
      yield
      puts "- This is bottom of yield"
  end

  #call methods and pass code block into method
  example_method {puts "- This put for yield"}

  # the output should be:
   - This is on top of yield
   - This put for yield
   - This is bottom of yield
   => nil

Moreover, yield we can:

  1. Pass parameters: when parameters passed to yield from metho_name, it will serve those parameters into the block. So we can use those parameters in our block to do magic for us.

    Note: The order of the arguments is important because the order you use to pass in the parameters is the order in which the block receives them.

    Example:
    
      # declare method which have yield inside
      def example_method
          puts "- This is on top of yield"
          yield("Rathanak", "Div2", 23)
          puts "- This is bottom of yield"
      end

      #call methods and pass code block into method
      example_method do |name, div, age|
          puts "- Name: #{name}, Dev: #{div}, age:#{age}"
      end

      # the output should be:
       - This is on top of yield
       - Name: Rathanak, Dev: Div2, age:23
       - This is bottom of yield
       => nil

  1. Get value: yield returns the value which return from the block.

    Example:

    # declare method which have yield inside
    def example_method
      puts "- This is on top of yield"
      puts "- The return from yield is: #{yield}"
      puts "- This is bottom of yield"
    end

    #call methods and pass code block into method
    example_method do
      "Rathanak"
    end

    # the output should be:
    - This is on top of yield
    - The return from yield is: Rathanak
    - This is bottom of yield
    => nil

More Example

Here are same examples of using ruby block:

  • Build my own Iterators: in this example, I'm going write code to make my own Iterator which have function same as map.

   def clone_map(array)
     new_array = []
     for num in array
       new_array.push yield num
     end
     new_array
  end

  clone_map([1, 2, 3]) do |number|
    number * number
  end

  #Output should be:
  1
  4
  9

Conclusion

Now, I hope you understand the true power of ruby code block. And the useful of yield in block which allows you to inject the code at some place into a method. Which mean your methods can work in different ways.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí