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

Trent Earl
  • 3,517
  • 1
  • 15
  • 20
0xSina
  • 20,973
  • 34
  • 136
  • 253

3 Answers3

5

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

user.birthday ? "x" : "y"
Community
  • 1
  • 1
Trent Earl
  • 3,517
  • 1
  • 15
  • 20
  • 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) – 0xSina Dec 02 '12 at 05:19
  • In `user.birthday?` the question mark is part of the method name, so there is not a ternary (?) operator. – Trent Earl Dec 02 '12 at 05:20
  • 2
    @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). – mu is too short Dec 02 '12 at 05:25
  • @muistooshort makes sense now :) – 0xSina Dec 02 '12 at 05:39
0

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

Krzysztof
  • 30
  • 3
-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

  • 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. – Jon Egeland Dec 02 '12 at 05:36
  • The error comes out because the variable and the method does not exist so you need to declarate them. – Dr. Astragalo Dec 02 '12 at 14:53