Integer loops

This is the final bit that I’ve written about using loops in Ruby. These are loops that either run a certain number of times, or that have some type of counter that is strictly integers.

The Goal

As I mentioned before, my goal here is to replace this very simple C fragment with Ruby.

for (i=0; i<10; i++) {
    printf("%d n",i);

Simplest loop

I should have mentioned this one first, but the step method is a more natural fit for the for loop. To run a block 10 times, simply do

10.times { |i| puts i }

Times passes the iteration number to the block (starting from 0.) This obviously also works if you assign (say) x=10 and then call x.times.

Counting loops

Ruby also provides the methods upto and downto, to start from one integer and count to another.

0.upto(9) {|i| puts i}

does what our for loop above does, but could start from any other integer. Downto goes the opposite way

9.downto(0) {|i| puts i}

If you are starting at zero, it makes more sense to use the times method, but these are a bit more flexible.


Ranges are a little more flexible, but the syntax and usage of them isn’t really straightforward. A range object is setup by two numbers seperated by two or three dots.

0..10     # 0 to 10
0...10    # 0 to 9

The .. version includes the last number, the … version does not. Once you have a range, you can use each to iterate over all the numbers. The only advantage I see here over upto and downto is that you have some more flexability in which numbers to iterate over. Ranges have method called reject and find_all that takes a block and keeps the numbers where the block returns false or not false, respectively. This could be helpful if you wanted odd or even numbers, for example.


For me personally, coming to Ruby from C type languages, making sense of loops took a fair amount of time to get my head around. Iterators are a great trick, but there are times in numerical work where they just don’t work. I’ve talked to some other people who have had similar issues, so hopefully this series has helped, and shown you something you didn’t know.

I certainly have not covered everything. There are variations that may make more sense depending on your code and personal taste. There are also more primitive things (such as while) where you should be able to do almost anything that doesn’t fit in what I’ve covered here, but I haven’t had to do that yet. Please let me know in the comments if i’ve missed anything clever.


Leave a Reply

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

You are commenting using your 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: