Ruby Simplified Part 4: Ruby Loops

Let’s look at some Ruby loop constructs: for, while, and until.

# .Each loop
x = 10
x.times do |i|        
    puts "#{i}"    # Starts at 0, ends at 9
end

# For loop
for i in 0..10 do  # Needs a range
    puts "#{i}"    # Starts at 0, ends at 10
end

# While loop
x = 0
while x < 10
    puts "#{x}"    # Starts at 0, ends at 9
    x += 1
end

# Until loop
x = 0
until x >= 10 do
    puts "#{x}"    # Starts at 0, ends at 9
    x += 1
end

Ruby also supports break and next, these are equivalent to break and continue in C#.

# Break
for i in 0..10
    if i > 5
        break      # Terminate the most internal loop
    end
    puts "#{i}"    # Will print 0 1 2 3 4 5
end

# Next
for i in 0..10
    if i < 5
        next
    end
    puts "#{i}"    # Will print 5 6 7 8 9 10
end
Advertisements

About soumya chattopadhyay
I live and work in Seattle, WA. I work with Microsoft technologies, and I'm especially interested in C#.

One Response to Ruby Simplified Part 4: Ruby Loops

  1. I was looking up a way to make non-slip socks as well as knee pads for my daughter. I haven’t tested this out yet, but a way to avoid the choking hazard could be to use the socks with out the nonslip dots on them then use the foam clothing paint to make them nonslip. I’ll be trying this out after I go to the craft store tomorrow. Come on http://tropaadet.dk/riversrobles48846081830

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: