DEV Community

Brittany
Brittany

Posted on

Day 4: #100DaysofCode - More Iterators

I wanted to review some more iterators as promised in my previous post

Times Iterator

The Times Iterator helps when you want to receive something n number of times. For example, if you wanted to say "HA!" six times you would use the times iterator like so:

6.times do
  puts "HA!"
end
Enter fullscreen mode Exit fullscreen mode

This will print "Ha!" to the screen 6 times. Like so:

HA!
HA!
HA!
HA!
HA!
HA!
Enter fullscreen mode Exit fullscreen mode

You could also take an argument and use interpolation like so:

5.times do |name|
  puts "Hello! #{name}"
end
Enter fullscreen mode Exit fullscreen mode

Just like an array index, the times index starts at 0. So the output above would look like the following:

Hello! 0
Hello! 1
Hello! 2
Hello! 3
Hello! 4
Enter fullscreen mode Exit fullscreen mode

Upto Iterator

The Upto Iterator allows you to could up to a number of your choice. But it has to be an ascending number, otherwise you will not receive output. I feel like this iterator is perfect for when you are trying to output a specific range of numbers, like so:

10.upto(20) do |n|    
  puts n    
end  
Enter fullscreen mode Exit fullscreen mode

Output:

10
11
12
13
14
15
16
17
18
19
20
Enter fullscreen mode Exit fullscreen mode

Downto Iterator

The Downto Iterator is pretty much the opposite of the Upto Iterator. In that it gives you a range of numbers descending. But just like the upto iterator, it has to be in a descending order, otherwise you will not receive output. Like so:

10.downto(5) do |n|    
  puts n    
end  
Enter fullscreen mode Exit fullscreen mode

Output:

10
9
8
7
6
5
Enter fullscreen mode Exit fullscreen mode

Step Iterator

The Step Iterator allows you to skip values by a number. So if you wanted to count by 5 to 30, you would use the step iterator like this:

(0..30).step(5) do|i| 
    puts i 
end
Enter fullscreen mode Exit fullscreen mode

Output:

0
5
10
15
20
25
30
Enter fullscreen mode Exit fullscreen mode

Each_Line Iterator

The Each_line Iterator is used to iterate over a new line in a string.

Syntax

string.each_line do |variable_name|
# code to be executed
end
Enter fullscreen mode Exit fullscreen mode

Example

"Now\nwe\nunderstand\niterators.".each_line do|i| 
puts i 
end
Enter fullscreen mode Exit fullscreen mode

Output:

Now
we
understand
iterators.
Enter fullscreen mode Exit fullscreen mode

Sources used for this blog:

Top comments (0)