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!

Answers


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)

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)

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

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

for cat in cats;cat.name;end

that should do it too.


Need Your Help

How to Convert String with printing control character to formatted String?

java printing

The problem is the source contains control character. Those control characters is invisible in Notepad. Text file viewer such as notepad does not display text in proper format.

ExtJS resizable windows keeping aspect ratio

extjs window aspect-ratio extjs6

I am trying to resize windows in ExtJS 6, and they resize fine, but I would like to resize them whilst maintaining the aspect ratio, but so far after an extensive google search and trying many opti...