The document discusses Ruby conditionals including if/else statements, case statements, and unless statements. If/else statements allow executing code conditionally based on boolean expressions. Case statements allow executing different code blocks based on the value of a variable. Unless statements provide a way to check if a condition is false.
3. Conditionals: if if age > 17 puts “can vote” end if age > 17 puts “can vote” else puts “attends school” end Statement Modifiers: do_something if x == 4 Other Syntax: if x == 4 then do_something end
4. Conditionals: if if age >= 21 puts “can drink” elsif age > 17 puts “can vote” else puts “too young” end
5. Checking for false if !(name == “superman”) … if not (name == “superman”) …
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
Editor's Notes
Unlike some languages with the 0 and empty string! Binds more tightly than than the “not” keyword so you do need parentheses for example 1, but don’t need parentheses for example 2
Conditionals are key to being able to make decisions in a programleft looks like every other languageparentheses are optional in ruby make sure to do ==, = is an assignment, == is a conditional testExplain putsright is a little different…people in ruby don’t like to type…english readableA statement modifier lets you move control structures at the end of an expression.
Conditionals are key to being able to make decisions in a programleft looks like every other languageparentheses are optional in ruby make sure to do ==, = is an assignment, == is a conditional testExplain putsright is a little different…people in ruby don’t like to type…english readableA statement modifier lets you move control structures at the end of an expression.
Unless can be awkward, especially with else. Usually you’ll want to use if for conditionals with else clauses.Occasionally unless is more readable:unless something is nil