The Array#each
method in Ruby allows you to iterate over each element of an array and perform a specific action on it. Here's how you can use it:
main.rb68 chars6 lines
In this example, each
is called on the array
object. Inside the block, which is delimited by do
and end
, the variable element
represents each element of the array in each iteration. In this case, it simply prints the element to the console.
The each
method is widely used in Ruby for iterating over arrays and performing operations on each element. You can also use it with an index:
main.rb134 chars6 lines
Here, each_with_index
is used instead of each
, which provides the current index along with the element in each iteration.
Note that each
does not return a new array; it is mainly used for performing a specific action on each element. If you need to transform the array or collect the results, you can use methods like map
or select
instead.
I hope this helps you understand how the Array#each
method works in Ruby!
gistlibby LogSnag