DEV Community

Kat
Kat

Posted on

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)