Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Logic and control flow in ruby

Logic and control flow in ruby

A little bit about the flow control

Valentine Ostakh

July 31, 2013
Tweet

More Decks by Valentine Ostakh

Other Decks in Programming

Transcript

  1. Let`s see foo = 42 && foo / 2 foo

    = 42 and foo / 2 NoMethodError: undefined method `/' for nil:NilClass 21
  2. Help methods def to_do puts ‘What to do?’ end def

    not_to_do puts ‘Nothing to do’ end def that_is_the_question?(question = false) question end
  3. When we are lazy job = that_is_the_question? job or not_to_do

    # => ‘Noting to do’ job || not_to_do # => ‘Noting to do’
  4. When we are lazy job or not_to_do # => ‘Noting

    to do’ job || not_to_do # => ‘Noting to do’ job or puts ‘Noting to do’ # => ‘Noting to do’ job || puts ‘Noting to do’ # => syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '(' job || puts 'Noting to do' job = that_is_the_question?
  5. The solution for control flow with ‘||’ is to place

    action in parentheses job || (puts ‘Noting to do’)
  6. The same situation when we a hard-working job = that_is_the_question?

    ‘of course’ job and to_do # => ‘What to do?’ job && to_do # => ‘What to do?’ job and puts ‘What to do?’ # => ‘What to do? job && puts ‘Noting to do’ # => syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '(' job || puts 'Noting to do' But now we know, how to fix this
  7. Control flow practice if job to_do end unless job not_to_do

    end to_do if job not_to_do unless job
  8. Control flow practice if job to_do end unless job not_to_do

    end to_do if job not_to_do unless job job and to_do job or not_to_do job or raise ‘LAZY boy’
  9. Control flow practice if job to_do end unless job not_to_do

    end to_do if job not_to_do unless job job and to_do job or not_to_do job or raise ‘LAZY boy’ Control flow with logic operators
  10. 1 || 2 && nil 1 or 2 and nil

    Some kind of magic
  11. 1 || 2 && nil # => 1 1 or

    2 and nil # => nil Some kind of magic
  12. 1 || 2 && nil # => 1 1 or

    2 and nil # => nil Some kind of magic Higher priority Lower priority
  13. What we have? use ‘&&’ and ‘||’ only for logic

    flow use ‘and’ and ‘or’ only for control flow Golden rule: