Computers have a very strict idea of when things are true and false.
(Unlike Stephen Colbert...)
Try the following in irb:
1 < 2
2 + 2 < 4
2 + 2 <= 4
2.even?
4.odd?
"apple".empty?
"".empty?
The magic word if
is called a CONDITIONAL.
if age < 18 then
puts "Sorry, adults only."
end
Ruby has a compact way of putting an entire if
expression on one line:
puts "Sorry, adults only." if age < 18
Note that:
The magic word else
allows BRANCHING.
if age >= 18 then
puts "allowed"
else
puts "denied"
end
Like a fork in the road, the program chooses one path or the other.
(In Ruby, then
is optional, so we usually leave it off, but if it makes your code clearer, go ahead and use it.)
Sadly, this expression:
2 + 2 = 4
causes a SyntaxError
. You need to do
2 + 2 == 4
instead. Why?
name = "Alice"
-- "assign the variable 'name' to the value 'Alice'"name == "Alice"
-- "does the variable 'name' contain the string 'Alice'?"This is confusing, and you should feel confused.
hello.rb
program should currently look something like this:puts "What is your name?"
name = gets.strip
puts "Hello, " + name + "!"
hello.rb
so that it doesn't always say hello!
You can make more complicated logical expressions using conjunctions like and
, or
, not
:
X and Y
means "are both X and Y true?"X or Y
means "is either X or Y (or both) true?"not X
means "is X false?"For example:
if age >= 18 or parent.gave_permission? then
puts "allowed"
else
puts "denied"
end
hello.rb
so that it says "Go away!" if the user's name is any one of a number of evil names/