Logic and control flow in ruby

Logic and control flow in ruby

A little bit about the flow control

15925832552071efd53de799a9152436?s=128

Valentine Ostakh

July 31, 2013
Tweet

Transcript

  1. To_do or not_to_do that_is_the_question? Ruby logic control flow guide

  2. What we know about logic in ruby?

  3. Logic operators: (by priority) ! && || not and, or

  4. What we know about control flow in ruby?

  5. Control flow: ?: if unless

  6. Hmm. Interesting, how we can to relate this parts?

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

    = 42 and foo / 2
  8. Let`s see foo = 42 && foo / 2 foo

    = 42 and foo / 2 NoMethodError: undefined method `/' for nil:NilClass 21
  9. 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
  10. When we are lazy job = that_is_the_question? job or not_to_do

    # => ‘Noting to do’ job || not_to_do # => ‘Noting to do’
  11. 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?
  12. The solution for control flow with ‘||’ is to place

    action in parentheses job || (puts ‘Noting to do’)
  13. 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
  14. Control flow practice if job to_do end unless job not_to_do

    end to_do if job not_to_do unless job
  15. 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’
  16. 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
  17. 1 || 2 && nil 1 or 2 and nil

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

    2 and nil # => nil Some kind of magic
  19. None
  20. 1 || 2 && nil # => 1 1 or

    2 and nil # => nil Some kind of magic Higher priority Lower priority
  21. They are the same, but so different

  22. What we have? use ‘&&’ and ‘||’ only for logic

    flow use ‘and’ and ‘or’ only for control flow Golden rule:
  23. And something else Always use regimented code style https:/ /github.com/styleguide/ruby

    https:/ /github.com/bbatsov/ruby-style-guide
  24. Ruby rocks!

  25. Thanks for your attention