Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. # Helper:
  2. # alternative `puts` with a non-nil return value
  3. # similar to many method calls which could be useful with logical operations
  4. def puts_with_true(arg)
  5. puts(arg)
  6. true
  7. end
  8.  
  9. # puts returns `nil` by default
  10. puts 1 && 2
  11. 2 # printed
  12. #=> nil
  13. # `1 && 2` is evaluated first, then it's printed
  14. # read: puts (1 && 2)
  15. # puts 2
  16.  
  17. puts 3 and 4
  18. 3 # printed
  19. #=> nil
  20. # `puts 3` is evaluated, returns `nil`
  21. # so `and 4` does not do anything
  22. # read: (puts 3) and 4
  23. # nil and 4
  24.  
  25. # when first part of the expression returns a truthy value:
  26.  
  27. puts_with_true 5 && 6
  28. 6 # printed
  29. #=> 6
  30. # `5 && 6` returns 6,
  31. # and this is printed and returned finally
  32. # read: puts_with_true (5 && 6)
  33. # puts_with_true 6
  34.  
  35. puts_with_true 7 and 8
  36. 7 # printed
  37. #=> 8
  38. # `puts_with_true 7` returns true,
  39. # therefore `and 8` is evaluated and returns `8` as final value
  40. # read: (puts_with_true 7) and 8
  41. # true and 8
  42.  
  43. # `and` has lower precedence than `&&`
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement