From: Sean O'Halpin Date: 2009-04-28T01:52:46+09:00 Subject: Re: Block Style 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. In the second you're not using the return value, so db.transaction do db[:count] += 1 db[:count] end would seem appropriate. I'm using this in DSL-type code: person = Person :name => "Arthur" do age 42 end and find it more aesthetically pleasing than: person = Person(:name => "Arthur") { age 42 } Just my tuppenceworth :) Regards, Sean