From: Robert Klemme Date: 2011-11-25T01:21:10+09:00 Subject: Re: Understanding Ruby blocks 2011/11/24 Jesús Gabriel y Galán : > On Thu, Nov 24, 2011 at 4:55 PM, Fily Salas wrote: >> I have been practicing Ruby and believe it or not the hardest part for >> me to understand (so far) is the concept of using blocks, why used them >> and how to use them. > > There are several benefits and use cases for using blocks. > >> For instance, I know I don't fully understand blocks but why would you >> use a block in the following situation. >> >> text = "Some Text" >> File.open('test_file.txt', 'a+') do |file| >>   file.write(text) >> end >> >> Why not just ...? >> >> text = "Some Text" >>  file = File.open('test_file1.txt', 'a+') >> file.write(text) >> ..why use a block instead? To make the code robust and ensure the resource is freed under all circumstances (especially exceptions, but also control flow which uses break, return or throw). > This is quite straightforward: in this situation the use case is that > you want to ensure that something happens before and after the block > code. In this case, the File#open method opens the file, then calls > the block and then ensures that the file is closed, even in the face > of an exception within the block. Shameless self advertizing: More explanations here: http://blog.rubybestpractices.com/posts/rklemme/001-Using_blocks_for_Robustness.html http://blog.rubybestpractices.com/posts/rklemme/002_Writing_Block_Methods.html > So, first use case: when you want code executed around code that is > not under your control. Yep, a block is just an anonymous function with a nice invocation syntax. In other programming languages one _sometimes_ uses template method pattern in such situations http://en.wikipedia.org/wiki/Template_method_pattern Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/