Is it possible to have a one line each block in Ruby?

Is there a one-line method of writing this each block in Ruby?

cats.each do |cat|
   cat.name
end

I'm trying to shorten the amount of code in my project. I'm using Ruby 1.9.2.

Thanks!


Solution 1:

Yes, you can write:

cats.each { |cat| cat.name }

Or simply:

cats.each(&:name)

Note that Enumerable#each returns the same object you are iterating over (here cats), so you should only use it if you are performing some kind of side-effect within the block. Most likely, you wanted to get the cat names, in that case use Enumerable#map instead:

cat_names = cats.map(&:name)

Solution 2:

Just remove the line breaks:

cats.each do |cat| cat.name end

Note, there are two different coding styles when it comes to blocks. One coding style says to always use do/end for blocks which span multiple lines and always use {/} for single-line blocks. If you follow that school, you should write

cats.each {|cat| cat.name }

The other style is to always use do/end for blocks which are primarily executed for their side-effects and {/} for blocks which are primarily executed for their return value. Since each throws away the return value of the block, it only makes sense to pass a block for its side-effects, so, if you follow that school, you should write it with do/end.

But as @tokland mentions, the more idiomatic way would be to write

cats.each(&:name)

Solution 3:

Another trick which I use for rails console/irb is to separate commands with ';' e.g.

[1,2].each do |e| ; puts e; end