From: "David A. Black" Date: 2009-04-28T07:44:17+09:00 Subject: Re: Block Style Hi -- Sean O'Halpin wrote: > On Sun, Apr 26, 2009 at 11:48 PM, James Gray wrote: >> I hate to be the guy to start another { � } vs. do � end thread, but I have >> some questions I would love to hear opinions on. >> >> I use to just use the rule of { � } for one-liners and do � end for the >> longer stuff. However, I've recently switched to trying out { � } for the >> times when I care about the return value and do � end for the times the >> block is for side effects. For the most part, I do like the new strategy, >> but sometimes I have trouble deciding which to use. >> >> Let me give two examples that have made me stop and think. >> >> First, tap() is Ruby 1.9 is a little tricky. I do care about the return >> value, but not the return value of the block, so which strategy should I >> use? It seems like do � end is more correct, but that seems a lot uglier in >> practice: >> >> arr.sort.tap do |sorted| >> p sorted >> end.whatever� >> >> Another example is with a transaction() method for a database. When using >> such a tool, I often end up with calls where I care about both the side >> effects (transactional behavior) and the return value: >> >> db.transaction { >> db[:count] += 1 >> db[:count] >> } >> >> Any thoughts on how edge cases like this mesh with the block strategy? >> >> James Edward Gray II >> >> >> > > I prefer {} when using blocks in a functional style, do..end when > using statements but I'm with Rick on the 'foolish consistency'. > > In your first example, it would appear that you ~are~ concerned with > the return value of the block as you call #whatever on it, so I'd use: > > arr.sort.tap { |sorted| > p sorted > }.whatever� > > assuming that the 'p sorted' stands for a multiline statement. In 1.9 > you can even do: > > arr > .sort > .tap { |sorted| p sorted } > .whatever� > > if you're so inclined. Though not in irb. (And, preferably, not anywhere, but that's probably a lost cause :-) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now out in PDF: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com