Ruby Blocks 101
January 20, 2006
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?
Entry Filed under: Uncategorized. .
19 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
1.
Wilhelm Tell | January 20, 2006 at 5:59 am
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.
2.
prerona | February 4, 2006 at 2:17 pm
interesting. thanks for the visit
3. michalkuklis.com Blog &ra&hellip | March 31, 2006 at 4:51 am
[...] Ruby is beautiful and very powerful. In order to start using it you have to understand how some things work. What was ne w for me are :symbols and blocks. Metaprogramming is also something to be aware of. [...]
4.
Efrén | April 6, 2006 at 2:50 pm
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.
5.
tma | August 7, 2006 at 12:13 pm
thanks for this really easy introduction to blocks
6.
David | September 5, 2006 at 7:28 am
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.
7.
yunus | February 2, 2007 at 2:23 am
Great!
Thanks for expainig yeild.
You explained really amazingly. I understand it and infact I mastered it by
reading your explaination.
thanks
Yunus
8.
Tim | April 8, 2007 at 6:52 pm
yay, now I finally know what the heck blocks are!
9. EstadoBeta » Archiv&hellip | August 6, 2007 at 5:35 am
[...] “@productos”. ¿Qué es eso de “yield”? Es algo que tiene que ver con los bloques en Ruby (lo que va entre los corchetes), pero eso lo podemos ver en otro artículo. La ventaja es [...]
10.
Douglas | August 30, 2007 at 6:31 pm
Yes!! Finally an explanation I understand. I have struggled with this concept for a while. Thank you.
11.
Douglas | August 30, 2007 at 6:34 pm
This one also helped… http://www.artima.com/intv/closures.html
Matz describes it as a nameless function passed into another function.
12. My Blog » Blog Arch&hellip | August 30, 2007 at 6:37 pm
[...] Blog post Sample… [...]
13.
van | September 16, 2007 at 1:34 am
Thank you very much.e
14.
Robert | December 4, 2007 at 12:25 am
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.
15.
Jonathan | December 14, 2007 at 11:43 pm
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).
16.
Adam | June 16, 2008 at 5:46 pm
Blocks are essentially lambda expressions, you’ll have the pleasure of using higher-order functions in any functional language you touch.
17.
matt | December 3, 2008 at 10:45 pm
Hi,
It might be useful to include a ‘real world’ example of how this sort of thing can be used. I understand the concept but can’t immediately see why I would want to do it (poor imagination on my part perhaps.)
matt
18.
James Gardner | January 22, 2009 at 9:46 am
I agree with Matt. Some practical application of where blocks might be used would be really useful. Though by no great stretch of the imagination I can easily think of some myself just from reading your article.
Thanks very much.
19.
Learning to read Ruby on &hellip | June 28, 2009 at 11:24 am
[...] 12. curly brackets { } – these are most of the time an indicator of a block. More on blocks here. [...]