I have one question

puts pin == pin_number ?  "Balance: $#{@balance}.":  pin_error

pin == pin_number ? puts "Balance: $#{@balance}." :  puts pin_error

First line of code is correct but second is wrong. Why?



puts is an action (put string). We cannot directly assign an action.


The reason behind this is rather complex, it comes from the language design. Syntactically the second method is more complicated and interpreter is simply not sure what you want to achieve.

In most style guides you will find advice to put each part of ternary operator into the parentheses and this practice solves the problem of complicated syntax:

(pin == pin_number) ? (puts "Balance: $#{@balance}.") : (puts pin_error)

Now it should work :slight_smile:


Ok! :slight_smile:
Thanks everybody!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.