tags:

views:

44

answers:

1

I am going through the Ruby tutorials from Learn to Program, and I am having a problem with a while loop.

This is what I want to do:

while y_now % 4
    y_now += 1
    puts y_now % 4
end
gets

I'm using the gets just to pause execution so I can see the output. (This is looking for a leap year, btw)

Anyways, when y_now % 4 = 0, the while loop continues, and I don't understand why, since this is different from all my previous experience.

I don't want someone to just fix my code though, I really want to understand why this happens. I've obviously just started Ruby, so whatever help I get is very much appreciated.

Note: This seems to be similar to this question, but with integers instead of strings.

+4  A: 

In Ruby only the nil object and a special false object are "false", everything else (including the integer 0) is "true". You should use while (y_now % 4) != 0.

Chris B.
OK I got it working now. I am having so much trouble because anytime I have an error, it just exits the command line immediately. Is there any way to have it spit out the error before exiting?
phoffer
@phoffer - outputting the error is default behavior, so absence of one might indicate that the script completed successfully without actually doing anything...
Matchu
@Matchu I am putting a gets at the end of my scripts for the time being so that it pauses before exiting. When it doesn't get there it just exits. I am opening the files from explorer, launching the command line interface. Should I open the command line first and run them through it that way?
phoffer
Wow, why didn't I think of that before? Answered my own question just now on my own. Thanks Matchu. Is there a way to have it output the error without exiting if I launch them from explorer?
phoffer
@phoffer - ahh, there ya go. I've run into this numerous times for bash scripts and the like - it hits an error, but the window disappears before I can read it, since the program is technically finished. Glad to help xD As far as a fix goes, there's probably not a clean way, but maybe you can be creative :/
Matchu
Maybe after I get used to putting a 20 line script together without 8 revisions :) I do like it though (used to php), just gotta get used to it.
phoffer