EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Ruby

Miscellaneous

Iterators in Ruby allow you to loop through collections like arrays, hashes, and ranges. Ruby provides several built-in methods to iterate over these collections.

Common Iterators:

1. each: Iterates over each element in a collection.
2. map: Creates a new array by applying a block to each element.
3. select: Returns an array of elements for which the block returns true.
4. reject: Returns an array of elements for which the block returns false.
5. reduce (also known as inject): Combines all elements of an enumerable by applying a binary operation.
6. times: Iterates a given number of times.
7. upto: Iterates from the current number up to the specified number.
8. downto: Iterates from the current number down to the specified number.
9. step: Iterates from the current number to the specified number, incrementing by the step value.

Examples:

1. each: The each iterator returns all elements of an array or hash, one by one.
Syntax:

collection.each do |variable_name|
  # code to iterate
end

Example:

# Using each iterator with a range
(0..5).each do |i|
  puts i
end

# Using each iterator with an array
letters = ['A', 'B', 'C']
letters.each do |letter|
  puts letter
end

2. Collect Iterator: The collect iterator returns all elements of a collection, either an array or hash, and can be used to transform elements.
Syntax:

result = collection.collect { |element| block }

Example:

# Using collect iterator to multiply each element
numbers = [1, 2, 3, 4]
result = numbers.collect { |x| x * 2 }
puts result

3. Times Iterator: The times iterator repeats a block of code a specified number of times, starting from 0 up to one less than the specified number.
Syntax:

t.times do |i|
  # code to execute
end

Example:

# Using times iterator
3.times do |i|
  puts i
end

4. Upto Iterator: The upto iterator starts from a number and continues up to the specified upper limit.
Syntax:

start.upto(limit) do |i|
  # code to execute
end

Example:

# Using upto iterator
1.upto(3) do |i|
  puts i
end

5. Downto Iterator: The downto iterator starts from a number and goes down to a specified lower limit.
Syntax:

start.downto(limit) do |i|
  # code to execute
end

Example:

# Using downto iterator
5.downto(2) do |i|
  puts i
end

6. Step Iterator: The step iterator is used when you want to skip a specified number of elements in a range during iteration.
Syntax:

range.step(step_value) do |i|
  # code to execute
end

Example:

# Using step iterator to skip by 2
(0..10).step(2) do |i|
  puts i
end

7. Each_Line Iterator: The each_line iterator iterates through each line in a string, often used when working with multi-line text.
Syntax:

string.each_line do |line|
  # code to execute
end

Example:

# Using each_line iterator
"Hello\nWorld\nRuby".each_line do |line|
  puts line
end
End of lesson.