Goalie Goalie - 4 years ago 155
Ruby Question

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!

Answer Source
cats.each(&:name)

However, note that Enumerable#each returns the same object you are iterating over (here cats), so it only makes sense to use it to do some kind of side-effect within the block. You probably meant to collect the cat names, use Enumerable#map:

cat_names = cats.map(&:name)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download