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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, you can write:
Or simply:
Note that
Enumerable#eachreturns the same object you are iterating over (herecats), 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: