+ 2

What does this code mean?

I don’t understand what the third line does. What is it? What do the ? and : do? Is it some kind of shorthand way of an if statement? x=0 y=1 puts x==y ? y : (x ? 2 : 3) #answer is 2

2nd Jan 2018, 11:46 AM
Arfaan
Arfaan - avatar
5 Answers
+ 6
puts (x == y ? y : (x ? 2 : 3)) x == y : false, so the ternary expression has (x ? 2 : 3) as a value x is 0, which is true in Ruby, so the value of the ternary expression is 2
2nd Jan 2018, 12:05 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 7
condition ? if_true : if_false is a ternary operator To know the value of it, your computer evaluate the condition. If it is true, then the value is what is between '?' and ':', else it is what is after ':'
2nd Jan 2018, 11:53 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 3
You are welcomed ! :)
2nd Jan 2018, 2:08 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
Thanks for your reply. Really helped 😊
2nd Jan 2018, 12:35 PM
Arfaan
Arfaan - avatar
+ 1
Ok I think I understand but can you please explain the third line in the code?
2nd Jan 2018, 12:03 PM
Arfaan
Arfaan - avatar