Question


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-32cN3/0/4?curriculum_id=5059f8619189a5000201fbcb

Hello,
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?

Thanks


#2

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


#3

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:


#4

Ok! :slight_smile:
Thanks everybody!


#5

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