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

Ruby

Ruby Problem Overview


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!

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

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 - Ruby

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

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

Solution 4 - Ruby

for cat in cats;cat.name;end

that should do it too.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGoalieView Question on Stackoverflow
Solution 1 - RubytoklandView Answer on Stackoverflow
Solution 2 - RubyJörg W MittagView Answer on Stackoverflow
Solution 3 - RubyZaharijeView Answer on Stackoverflow
Solution 4 - RubyRobert SSView Answer on Stackoverflow