DEV Community

Kat
Kat

Posted on

2

Ruby Syntax: Each

Today's module introduced a really interesting array method in Ruby: each. This is an efficient way to loop over elements in an array in Ruby.

"Each" can be used with "do" and a block variable to create an iterative loop rather than using a while loop or for loop and has the benefit of not requiring a value to be incremented in order to move to the next element in the array. Also, it doesn't require us to know the number of elements in the array, as would be the case if we used .times.

This makes our code more concise!

Here is an example of how to print each element in an array using .each:

my_array = ["cat", "dog", "hamster", "frog", "parakeet"]
my_array.each do |animal|
  pp animal
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay