From: "Jesús Gabriel y Galán" Date: 2011-11-25T01:01:39+09:00 Subject: Re: Understanding Ruby blocks On Thu, Nov 24, 2011 at 4:55 PM, Fily Salas wrote: > Hi, > > 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? 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. So, first use case: when you want code executed around code that is not under your control. Another use case is when you provide a generic functionality that can applied to many situations, but you want to leave the exact detailed behavior to the client code. For example, the Enumerable#each method provides its clients with the capability of traversing an enumerable instance, doing something with each element one at a time. What you do with the element is responsibility of the client code, so the each method just accepts a block to achieve that. Hope this helps and I hope the concept clicks soon, because it's one of the things that make Ruby so wonderful. Jesus. > 1-What would be a good rule of thumb to know when to use blocks? > 2-What would be the easiest way to understand block? > 3-Can someone be so kind and explain block a little bit? > > Thanks a lot for all of your help! > Learning a lot in this forum. Awesome people! > > -- > Posted via http://www.ruby-forum.com/. > >