The each method is a fundamental method used for iterating over elements in a collection, such as arrays, hashes, or ranges. It's commonly used for performing an action on each element of the collection. Here's an explanation of the each method:
Syntax
collection.each do |item|
# Code block to be executed for each item
end
Parameters
collection: The collection (array, hash, range, etc.) over which iteration is to be performed.
item: Represents each individual element of the collection during iteration.
Usage
Array: Iterate over each element of an array.
array = [1, 2, 3, 4, 5]
array.each do |item|
puts item
end
Hash: Iterate over each key-value pair of a hash.
hash = { "a" => 1, "b" => 2, "c" => 3 }
hash.each do |key, value|
puts "#{key}: #{value}"
end
Range: Iterate over each element in a range.
(1..5).each do |num|
puts num
end
Behavior
Executes the block of code for each element in the collection.
The block's parameter (e.g., item, key, value, etc.) represents each individual element during each iteration.
After executing the block for each element, the each method returns the original collection.
Example:
array = [1, 2, 3, 4, 5]
array.each do |item|
puts item * 2
end
# Output:
# 2
# 4
# 6
# 8
# 10
Notes
The each method is commonly used in Ruby for iteration tasks, offering a clean and readable syntax.
It's important to note that each does not modify the original collection. If you need to modify the collection, you might want to use methods like map, select, or reject, depending on your requirements.
Happy coding!
theGlamTechie
Top comments (0)