This document discusses Ruby conditionals and control flow statements including if/else, unless, case, and truth values. It provides examples of using if/else statements with different conditions and modifiers. It also demonstrates using unless, case statements with ranges, regular expressions, and different data types, and truth values in Ruby.
3. CONDITIONALS: IF
if age > 17
puts “can vote”
Statement Modifiers:
end do_something if x == 4
Other Syntax:
if x == 4 then do_something end
if age > 17
puts “can vote”
else
puts “attends school”
end
4. CONDITIONALS: IF
if age >= 21
puts “can drink”
elsif age > 17
puts “can vote”
else
puts “too young”
end
6. UNLESS
• “unless” provides us with another way of checking if a
condition is false:
unless human
status = "superhero"
end
status = "superhero" unless human
7. CASE
case superhero
when "superman"
city = "metropolis"
when "batman"
city = "gotham_city"
else
city = "central_city"
end
8. CASE REFACTORING
city = case superhero
when "superman"
"metropolis"
when "batman"
"gotham_city"
else
"central_city"
end
9. CASE
case num
when 1
puts "one"
when 2..5
puts "that is
small"
else
puts "pretty big"
end
10. CASE
case name
when "Sarah"
puts "awesome"
when /Mr.*/
puts "formal guy"
else
puts "whatever"
end
11. CASE
case args
when String
puts "Got a String"
when Array
puts "Got an Array”
when Hash
puts "Got a Hash"
end
Notes de l'éditeur
\n
Unlike some languages with the 0 and empty string\n! Binds more tightly than than the “not” keyword so you do need parentheses for example 1, but don’t need parentheses for example 2\n
Conditionals are key to being able to make decisions in a program\n\nleft looks like every other language\n\nparentheses are optional in ruby \nmake sure to do ==, = is an assignment, == is a conditional test\n\nExplain puts\n\nright is a little different…people in ruby don’t like to type…english readable\nA statement modifier lets you move control structures at the end of an expression.\n
Conditionals are key to being able to make decisions in a program\n\nleft looks like every other language\n\nparentheses are optional in ruby \nmake sure to do ==, = is an assignment, == is a conditional test\n\nExplain puts\n\nright is a little different…people in ruby don’t like to type…english readable\nA statement modifier lets you move control structures at the end of an expression.\n
\n
Unless can be awkward, especially with else. Usually you’ll want to use if for conditionals with else clauses.\n Occasionally unless is more readable:\n unless something is nil\n