For like loops

In my earlier post, I talked about the use of iterators instead of pure loops in Ruby. When you can use them, they work wonderfully, but sometimes you just need to make the code loop. My impression is that these are the things that are not as clearly explained in Ruby material, and is likely to be a thorn in your side if you are coming to Ruby from something like Fortran or C where you have more control over the control flow of your code.

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);

A note about blocks

I didn’t mention this before, but all of these looping techniques work by accepting a “block.” If you are new to Ruby this concept will hound you untill it finally makes sense. I am not going to be able to explain blocks here, so if you aren’t sure about them I would suggest you do some reading on those first. This won’t make much sense untill they are a little more clear.

Step – the one that works with decimals

If you need start/end/step values that are not integers. This is (I think) your only real option. It is a method built into the numeric classes, and you pass it the ending point, and the step value. Like this

0.0.step(9.0, 1.0) do |x|
  puts x

The block is passed values from step, untill the value would be greater than the end number (9.0 in this case) so this is more like

for (x=0.0; x<=9.0; x+=0.1)

where the <= instead of < can potentially throw you.

I have used this most recently for mapping out a complicated function using

0.0.step(0.8,0.01) do |x|
  0.0.step(0.8,0.01) do |y|
    #calculate function value and do something with it

this will also count backwards if the start is higher than the end number, with a negative step.

Fencepost errors

Not to belabor the point about iterators, but notice that I had to change to i<10 to i<=9 when the type of test changed. If you forget to do this you end up with one more or less number than you were expecting. These are called fencepost errors based on the trick question kind of thing of ‘how many fence posts do you need for 3 sections of fence’ where the answer is not 3 but 4.

Finally, Ruby offers a bunch of methods for integer loops. I will talk about in the next post.


2 Responses to For like loops

  1. […] my next post I will talk about the non-iterator loops in […]

  2. […] For like loops In my earlier post, I talked about the use of iterators instead of pure loops in Ruby. When you can use them, they […] […]

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: