-2

In Ruby, I've just noticed that:

  • puts true and false returns true, while
  • puts (true and false) and puts false and true return both false.

What is the logic/reason behind this behaviour?

ebosi
  • 1,285
  • 5
  • 17
  • 37
  • Can it be because `puts` is not a keyword - its a method that returns nil? Because `true and false` give nil without puts. https://ruby-doc.org/core-2.5.1/Kernel.html#method-i-puts – max Sep 03 '18 at 15:14
  • 1
    Technically, I'd say it returns `nil`, not `true` or `false`, and outputs `true`. e.g. if you execute the statement `result = (puts true and false)`, `result` will be nil. This is because `puts` returns `nil`. `nil and false` evaluates to `nil`. – dinjas Sep 03 '18 at 21:53
  • 1
    The first one doesn't return `true`, it prints `true`. The second examples do not return `false`, they print `false. You are confusing the return value with the printed value. – sawa Sep 04 '18 at 03:46
  • @sawa: Indeed, you are right. What got me confused is that I used an online IDE that didn't output return values… – ebosi Sep 04 '18 at 09:26

1 Answers1

2

Because puts binds stronger than and: your code is equal to

(puts true) and false
true
#=> nil

You can check operators precedence in docs.

To get what you could use &&, which has higher precedence than and:

puts true && false
false
#=> nil
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145