Ruby Conditionals - IF Statements
(Page 2 of 4 )
As a nerdy kid, my friend and I would make Qbasic programs whose sole purpose was to insult people. This was back before people even knew what a computer was (I'm talking an old Apple IIe and no user interface). We would program little IF Statements that would ask your name, and if you entered a certain name, it would tell you you had some serious weight issues, or that your mama was so dumb, she threw a rock at the ground and missed it. Insult gold is what I'm telling you. And all thanks to the good old If Statement.
Try the following code:
hammer_time = 2
if hammer_time > 1 && hammer_time < 3 # begins IF conditional
puts “Hammer Time!” # tells it what to do if the condition is met
end # ends the conditional
If you run this program, you will clearly see that it is indeed, Hammer Time.
In the above code, we are saying that if the variable hammer_time is greater than 1 AND less than three, print the words, “Hammer Time!” to the screen. We give the clause AND by using the && operator.
We could also use the OR (||) operator to specify that we want the value to equal this OR that. Like so:
hammer_time = 2
if hammer_time >1 || hammer_time < 3
puts “Hammer Time!”
end
Again, since hammer_time meets the criteria, “Hammer Time!” is written to the screen.
We could have made it even simpler had we wanted:
hammer_time = 2
if hammer_time > 1
puts “Hammer Time!”
end
All of the above code is an example of a Boolean condition. Boolean refers to a true/false situation (or Yes/No or On/Off). In other words, it's not like those multiple choice questions you got on your test.
Next: Else Clause >>
More Ruby-on-Rails Articles
More By James Payne