Solved

Conditional Operator

Posted on 2008-10-20
3
715 Views
Last Modified: 2013-11-13
Hi, is there a conditional operator in Ruby like the ? in C/C#, ie

x = y == nil ? 0 : 1

I know you can do

x = if (y == nil) then 0 else 1 end

Just wondering if the more compact is possible in Ruby.  

Thanks!
0
Comment
Question by:ARACK04
  • 2
3 Comments
 
LVL 60

Accepted Solution

by:
Geert Bormans earned 500 total points
ID: 22760863
you can use the ? in ruby as in C

x = y == nil ? 0 : 1

will work
0
 

Author Comment

by:ARACK04
ID: 22760889
Huh - so I guess the above would also be

x = y.nil? ? 0 : 1

Cool - I feel like I fool for not trying it - I ASSumed since a lot of the methods ended in ?  it wouldn't also be an operator.

Thanks again.
0
 
LVL 60

Expert Comment

by:Geert Bormans
ID: 22760914
yep,
x = y.nil? ? 0 : 1
would be the nicer, more ruby-like form
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: narshlob
If you've ever programmed in Ruby and have come across either a proc or a lambda, you might have been wondering what the difference is between the two and when you would use one over the other. This article will try to explain the difference between…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question