I love Ruby blocks! The idea behind them is just very very neat and convenient.
I have just looked back over my code from the past week or so, which is
The whole thing would be more readable as:
if something.do_stuff
#successful code
else
#unsuccessful code
end
or to use a common rails idiom:
if @user.save
render :action=>:show
else
@user.errors.each{|attr,msg| logger.info "#{attr} - #{msg}" }
render :action=>:edit
end
IMHO, avoiding the return of a boolean value is overuse of code blocks.
A block makes sense if . . .
open("fname") do |f|
# do stuff with the file
end #don't have to worry about closing the file
In this case, you avoid adding the return value to calling scope. This also often makes sense with multiple return values.
something.do_stuff do |res1, res2|
if res1.foo? and res2.bar?
foo(res1)
elsif res2.bar?
bar(res2)
end
end #didn't add res1/res2 to the calling scope
You see this in some of the rails helpers:
<% content_tag :div do %>
<%= content_tag :span "span content" %>
<% end -%>
And of course iterators are a great use case, as they're (considered by ruby-ists to be) prettier than for loops or list comprehensions.
Certainly not an exhaustive list, but I recommend that you don't just use blocks because you can.