Upcoming SlideShare
×

# Eloquen - Chapter 2 - use right control

350 views

Published on

a presentation about chapter 2 - Use Right Control in Eloquent Book.

Published in: Education
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

### Eloquen - Chapter 2 - use right control

1. 1. Chapter 2Choose The Right ControlThere are 4 point:• If, Unless, While & Until• Use each, not for• Case Logic• False Value
2. 2. 1. If, Unless, While & Untilif & unless:Usage:if condition unless condition do_something do_somethingend end# do_something # do_somethingwhen condition is true. when condition is false.
3. 3. 1. If, Unless, While & Untilif & 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. 4. 1. If, Unless, While & Untilif & unless with else statement:Code:If hungry? If full? “eat something” “stop eating”else else “stop eating” “eat something”end end
5. 5. 1. If, Unless, While & Untilif & unless with else statement:**Not: never use unless with else statementunless hungry? “stop eating”else “eat something”end
6. 6. 1. If, Unless, While & UntilTernary:Usage:condition ? true : falseCode:hungry? ? eat_something : stop_eatingfull? ? stop_eating: eat_something
7. 7. 1. If, Unless, While & Untilwhile & until:Usage:while condition until condition do_something do_somethingend end# loop do_something # loop do_somethingwhen condition is true. when condition is false.
8. 8. 1. If, Unless, While & Untilwhile & until:Code: one line statementeat_something while hungry?stop_eating until hungry?stop_eating while full?**Not: stop_eating while !hungry?
9. 9. 2. Use each, Not forCode: **Not:array.each do |arr| for arr in array puts arr puts arrend end when use this,array.each { |arr| puts arr } ruby will call each. 2 level calling.
10. 10. 3. Case LogicCode:case titlewhen War And Peace puts Tolstoywhen Romeo And Juliet puts Shakespeareelse puts "Dont know"end
11. 11. 3. Case Logicauthor = case title when War And Peace then Tolstoy when Romeo And Juliet then Shakespeare else "Dont know" end
12. 12. 3. Case Logiccase titlewhen /War And .*/ puts Maybe Tolstoy?when /Romeo And .*/ puts Maybe Shakespeare?else puts Absolutely no idea...end
13. 13. 4. False ValueOnly 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
14. 14. Thank You