Intro to Ruby - Loops

Ruby

Overview

The following is a look at Ruby loops such as while, until, and loop. These should be familiar to you from other languages but make sure to take a look at the map, inject (a.k.a. reduce), and select methods. These are powerful looping constructs that will allow you to accomplish a lot in only a single line of code. To learn more about these loops, take some time to read “functional programming and looping and Understanding map and reduce as originally discussed on the Rails Spikes site.

Code


class Loopy
  COLORS = ["red", "blue", "green", "white", "yellow"]

  def print_time_1
    future = Time.now + 5
    while Time.now < future do
      puts Time.now
      sleep 2
    end
  end

  def print_time_2
    future = Time.now + 5
    until Time.now > future do
      puts Time.now
      sleep 2
    end
  end
end

loopy = Loopy.new

# A "for each" loop that prints each color in an array.
puts "01 For Each\n\n"
Loopy::COLORS.each {|color| puts color}

# A "for in" loop that performs the same logic as the "for each" loop above.
puts "\n02 For In\n\n"
for color in Loopy::COLORS do
  puts color
end

# An example of a while loop that prints time while a condition is not met.
puts "\n03 While\n\n"
loopy.print_time_1

# An example of until loop that prints time until a condition is met.
puts "\n04 Until\n\n"
loopy.print_time_2

# An example of a "loop" loop.  Again using time to break out, otherwise the loop will run indefinitely.
puts "\n05 Loop\n\n"
time = Time.now + 1
count = 0
loop do
  puts "Hey, I'm inside the loop" if count == 0
  count += 1
  break if Time.now > time
end
puts "Exited loop, total count: #{count}"

# An example of the a mapping loop that generates a new array of colors that are all uppercase.
puts "\n06 Map\n\n"
puts Loopy::COLORS.map {|color| color.upcase}

# The following reduces a range of numbers to a single value.
puts "\n07 Reduce\n\n"
puts (1..5).inject(0) {|sum, value| sum + value}

# The following returns a new array of colors but only those that have the letter 'l' in them.
puts "\n08 Select\n\n"
puts Loopy::COLORS.select {|color| color['l'] }

Output

01 For Each

red
blue
green
white
yellow

02 For In

red
blue
green
white
yellow

03 While

Sun Mar 01 10:29:05 -0700 2009
Sun Mar 01 10:29:07 -0700 2009
Sun Mar 01 10:29:09 -0700 2009

04 Until

Sun Mar 01 10:29:11 -0700 2009
Sun Mar 01 10:29:13 -0700 2009
Sun Mar 01 10:29:15 -0700 2009

05 Loop

Hey, I'm inside the loop
Exited loop, total count: 719438

06 Map

RED
BLUE
GREEN
WHITE
YELLOW

07 Reduce

15

08 Select

blue
yellow

Download

The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 12-loops.rb.

What’s Next

Exceptions

Tags:

Thursday, March 5th, 2009 Software

No comments yet.

Leave a comment

You must be logged in to post a comment.