Ternary Operator


(Simon Bailey) #1

Is there some sort of ternary operator in Ruby like the one in C++?

eg.

greaterThanFive = (x > 5) ? “yes” : “no”;


(James) #2

Is there some sort of ternary operator in Ruby like the one in C++?

eg.

greaterThanFive = (x > 5) ? “yes” : “no”;

Yes:

greaterThanFive = (x > 5) ? “yes” : “no”

:slight_smile:

James

···

(Thomas Rivas) #3

Simon Bailey wrote:

Is there some sort of ternary operator in Ruby like the one in C++?

eg.

greaterThanFive = (x > 5) ? “yes” : “no”;

Yes, to my newbie-knowledge it is borrowed from C: condition? expr1 : expr2

i.e.,

print "This page has been viewed ", counter, " time"
print (counter == 1) ? “” : “s”


(Carlo Teubner) #4

Is there some sort of ternary operator in Ruby like the one in C++?

Yup. You don’t need it though, because in Ruby, the if statement returns a value, eg:

greaterThanFive = if x > 5 then “yes” else “no” end

The ternary operator is mainly good for obfuscation, eg:

class Fixnum; def ?;??end end
puts ??.
?? ??:?:

g,d&r

-Carlo