0xSina
0xSina

Reputation: 21553

Ternary operator syntax error

New to ruby, exploring the teranary operator.

This works just as expected:

5==5? "x" : "y"

returns "x", as everything in ruby is an expression.

But, this doesn't...

user.birthday? "x" : "y"

It's suppose to check if birthday is nil, and return the appropriate string. But it gives me a syntax error:

syntax error, unexpected ':', expecting $end
user.birthday? "x" : "y"
                    ^

What's so different about this statement comapred to the other?

Thanks

Upvotes: 1

Views: 1646

Answers (3)

Krzysztof
Krzysztof

Reputation: 30

In your case user.birthday? ? 'x' : 'y' will do the trick if you want to check if birthday is not nil/false.

Upvotes: 0

Dr. Astragalo
Dr. Astragalo

Reputation: 9

ruby is a Object Oriented Programming language so all method definitions are inheritance from a class, and that comes like a "true",try this:

class User

def birthday(confirm)
    return true
end

end

us = User.new()

us.birthday("My birthday")

rep= us.birthday("My birthday") ? "x": "y"

puts rep

Upvotes: -2

Trent Earl
Trent Earl

Reputation: 3607

Methods can and often do end with a question mark in ruby.

user.birthday ? "x" : "y"

Upvotes: 5

Related Questions