teach me array#each what it does and how? in ruby

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.rb
array = [1, 2, 3, 4, 5]

array.each do |element|
  puts element
end
68 chars
6 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.rb
array = ["apple", "banana", "cherry"]

array.each_with_index do |element, index|
  puts "Element at index #{index} is #{element}"
end
134 chars
6 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!

related categories

gistlibby LogSnag