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 G. II