Ruby Iterators

Here are some Ruby Iterators and description of how they can be used:

Iterate through the block 3 times, n starts at 0 and ends at 2 and is incremented by 1 each time.
n is the block variable.

3.times do |n|
  puts n
end

Iterate through the block 3 times, starting at 1 and ending at 3, each time incrementing by 1.
n is the block variable.

1.upto(3) do |n|
  puts n
end

Iterate through the block 3 times, starting at 3 and ending at 1, each time decrementing by 1.
n is the block variable.

3.downto(1) do |n|
  puts n
end

Iterate through the block 3 times by specifying a Range starting at 1 and ending at 3, each time incrementing by 1. A Range (1..3) is specified and is actually an object of type ‘Range’.

(1..3).each do |n|
  puts n
end

Iterate through the block a range of 2 through 10 times, starting at 2 and ending at 10, each time incrementing by the step specified (2 in this case). A Range (2..10) is specified and is actually an object of type ‘Range’.
n is the block variable.

(2..10).step(2) do |n|
  puts n
end

Iterate through the block however number of newlines there are in the String specified. The each_line iterator can be used with Strings only since Strings have newlines and it doesn’t make sense for other objects to have newlines.
line is the block variable.

"hello\nworld\nhow\nare\nyou?".each_line do |line|
puts line
end

Iterate through the block however number of characters there are in the String specified. The byte form of the character is passed into the block as a parameter one_byte and is converted to its character equivalent before being printed to the screen.
one_byte is the block variable.

"hello world".each_byte do |one_byte|
printf "%c\n", one_byte
end

Iterate through the block however number of elements there are in the array, passing the index of the elements to the block as an argument i. By contrast, the each iterator would have passed in the value of each element itself rather than the index.
i is the block variable.

[1, 4, 5, 7, 10, 12].each_index do |i|
  puts i
end
VN:F [1.9.22_1171]
Rating: 3.8/5 (4 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)
Ruby Iterators, 3.8 out of 5 based on 4 ratings
Facebook Twitter Email

3 Comments to “Ruby Iterators”