1

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

3 Answers 3

5

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

user.birthday ? "x" : "y" 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. But 5==5? returns a boolean, and user.birthday? does too. So why doesn't it work like that? In both cases, the syntax comes down to: BOOL IFSTATEMENT : ELSESTATEMENT (PS - I will accept your answer in 7 minutes)
In user.birthday? the question mark is part of the method name, so there is not a ternary (?) operator.
@0xSina: Add the implied parentheses to user.birthday? "x" : "y" and you get user.birthday?("x" : "y") (which doesn't make any sense at all).
@muistooshort makes sense now :)
0

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

Comments

-2

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

2 Comments

I'm not sure exactly what you are saying here, but I'm pretty sure it has nothing to do with the issue. The problem is that birthday? is acting like a method instead of a ternary operation.
The error comes out because the variable and the method does not exist so you need to declarate them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.