All About Ruby



Ruby Blocks 101

One of the difficulties you might have with jumping into Ruby on Rails is that you need to learn the Ruby language (yes, you do ;) ). And if you come from the PHP background as I am, the single weirdest thing in Ruby would be the notion of blocks. I have never seen the blocks in any other language. The concept seems beautiful, but completely unrelated to anything I know about programming.

The concept of blocks is logical and intuitive, but most likely very different from the way you experienced programming. Blocks are like alien logic - something so basic, that it changes the meaning of everything. Think of how an amphibian race of super-intellectual beings would differ from humans - this is how different the blocks concept is from your PHP functions.

As blocks are the basic structures of Ruby, chances are you have already seen them and did not really understand what was going on. I hope this post will be able to help you out with getting the hang of the concept really quickly.

So let’s start with an easy example. Run irb (cmd irb.bat) and define the method:

def aliens
i = 1
j = 2
yield(i, j)
end

This method just assigns two variables and then passes those variables to the block. Now let’s call the block:

aliens { |x, y| puts x, y }

It works as follows: aliens method is called, with Ruby recognizing that this method has a block attached to it. Once the yield is encountered within the aliens, it is passed to the block together with any parameters in the brackets. As i and j are local variables, we need to define the first and second variable to be used to hold i and j values. Finally we have the Ruby code that does something with those parameters. Puts just displays the values of i and j on screen. But you can do something more complicated:

aliens { |x, y| puts x+y*y }

This should display 5.

If you are not confused at this moment, great - you have almost mastered the blocks ;). If you are, think about the aliens as a function that allows three parameters - x, y and some arbitrarily complex Ruby code. Yield is the place where this code is executed. To make sure that this is the case, try this: (copy the code, save it to blocks.rb in your project directory and run ruby blocks.rb)

def aliens
i = 1
j = 2
yield(i, j)
i = “magick”
return nil
end

aliens { |x, y| puts x }

The script should print “1″. This is easy stuff. (Pedantic note. You can ignore “return nil“, it is there because Ruby returns the last value in the function (=method) as the result of the function, so if you run the code above in irb without “return nil”, you will see that aliens actually returns “magick”)

Another cool feature is the ability to test whether the method has a block. Check out this code:

def aliens
if block_given?
  i = 1
  j = 2
  yield(i, j)
 else puts “magick”
 end
end

aliens { |x, y| puts x }
aliens

In that case if the block is provided to the method, we execute the if statement, otherwise we execute the else statement. So, as a result the script should print “1″ and “magick”.

How cool is that? :)


Trackbacks & Pingbacks

  1. michalkuklis.com Blog » Blog Archive » ruby way huh? pingbacked on 2 years, 4 months ago
  2. EstadoBeta » Archivo » Ruby pingbacked on 1 year ago
  3. My Blog » Blog Archive » Ruby Blocks pingbacked on 11 months, 3 weeks ago

Comments

  1. 1 Wilhelm Tell says:

    If you programmed in C++ before, then chances are that you’ve seen blocks before.

    The analog of Ruby’s block in C++ is the STL iterator. The beauty about Ruby is that blocks are part of the language, wherease in C++ iterators are ready for use only for the STL; for a completely custom-made class you’d probably need to create a custom-made iterator.

    Then again, one may claim that the beauty about C++ is that the syntax is simple, and anything that is more complex can be created by the user.

    Posted 2 years, 7 months ago
  2. 2 prerona says:

    interesting. thanks for the visit

    Posted 2 years, 6 months ago
  3. 3 Efrén says:

    We noticed that your blog have some Ruby On Rails releated content, and that
    is why we would like to invite you to register yourself and your
    blog at RubyCorner, a directory of Ruby related blogs:

    http://www.rubycorner.com/

    We like to think about RubyCorner as a “meeting place” for the
    community, also as a “focal point” where the people new to this
    technology can quickly tune into the pulse of the community.
    Registering your blog will help build a valuable resource for
    this growing community.

    Posted 2 years, 4 months ago
  4. 4 tma says:

    thanks for this really easy introduction to blocks :)

    Posted 2 years ago
  5. 5 David says:

    Thanks for taking the time to post this. Immediately after reading your first example I got it! Coming from PHP it’s taking a little time to understand certain Ruby concepts I’ve never been exposed to before.

    Posted 1 year, 11 months ago
  6. 6 yunus says:

    Great!
    Thanks for expainig yeild.
    You explained really amazingly. I understand it and infact I mastered it by
    reading your explaination.

    thanks
    Yunus

    Posted 1 year, 6 months ago
  7. 7 Tim says:

    yay, now I finally know what the heck blocks are!

    Posted 1 year, 4 months ago
  8. 8 Tim says:

    Good job, here and there!a

    Posted 1 year ago
  9. 9 Douglas says:

    Yes!! Finally an explanation I understand. I have struggled with this concept for a while. Thank you.

    Posted 11 months, 3 weeks ago
  10. 10 Douglas says:

    This one also helped… http://www.artima.com/intv/closures.html
    Matz describes it as a nameless function passed into another function.

    Posted 11 months, 3 weeks ago
  11. 11 van says:

    Thank you very much.e

    Posted 11 months, 1 week ago
  12. 12 Robert says:

    Hey, fantastic job. I now actually understand how to make methods that use blocks.

    However, damn you at the same time. I have started rewriting my methods now to take advantage of this new found knowledge :)

    Seriously though, thanks.

    Posted 8 months, 3 weeks ago
  13. 13 Jonathan says:

    Actually functors are the C/C++ equivalent and not iterators. It isn’t possible to customize the logic executed per iteration using STL iterators alone. You have to combine iterators with functors to get closure/block behavior. (And, in C#, anonymous delegates do the job).

    Posted 8 months, 1 week ago
  14. 14 Adam says:

    Blocks are essentially lambda expressions, you’ll have the pleasure of using higher-order functions in any functional language you touch.

    Posted 2 months ago

Leave a Comment

(required)

(required)



Formatting your comment
Back to Top | Textarea: Larger | Smaller