1. Chapter 2
Choose The Right Control
There are 4 point:
• If, Unless, While & Until
• Use each, not for
• Case Logic
• False Value
2. 1. If, Unless, While & Until
if & unless:
Usage:
if condition unless condition
do_something do_something
end end
# do_something # do_something
when condition is true. when condition is false.
3. 1. If, Unless, While & Until
if & unless without else statement:
Code: one line statement
“eat something” If hungry?
“stop eating” unless hungry?
“stop eating” if full?
**Not: “stop eating” if !hungry?
4. 1. If, Unless, While & Until
if & unless with else statement:
Code:
If hungry? If full?
“eat something” “stop eating”
else else
“stop eating” “eat something”
end end
5. 1. If, Unless, While & Until
if & unless with else statement:
**Not: never use unless with else statement
unless hungry?
“stop eating”
else
“eat something”
end
7. 1. If, Unless, While & Until
while & until:
Usage:
while condition until condition
do_something do_something
end end
# loop do_something # loop do_something
when condition is true. when condition is false.
8. 1. If, Unless, While & Until
while & until:
Code: one line statement
eat_something while hungry?
stop_eating until hungry?
stop_eating while full?
**Not: stop_eating while !hungry?
9. 2. Use each, Not for
Code: **Not:
array.each do |arr| for arr in array
puts arr puts arr
end end
when use this,
array.each { |arr| puts arr } ruby will call each.
2 level calling.
10. 3. Case Logic
Code:
case title
when 'War And Peace'
puts 'Tolstoy'
when 'Romeo And Juliet'
puts 'Shakespeare'
else
puts "Don't know"
end
11. 3. Case Logic
author = case title
when 'War And Peace' then 'Tolstoy'
when 'Romeo And Juliet' then 'Shakespeare'
else "Don't know"
end
12. 3. Case Logic
case title
when /War And .*/
puts 'Maybe Tolstoy?'
when /Romeo And .*/
puts 'Maybe Shakespeare?'
else
puts 'Absolutely no idea...'
end
13. 4. False Value
Only nil and false are treated as false.
Code:
@first_name = ‘Chaung‘ unless @first_name
@first_name ||= ‘Chaung’
**Note: do not use this for boolean type
@boolean = false
@boolean ||= true