The Question Mark Operator in Ruby on rails
By: Brian Marick
You’ll often find yourself selecting between two alternative values for a variable. That can be done like this:
if input < 0
output = 0
else
output = input
end
But it seems wrong to take up five lines for such a simple idea. You can reduce it to two by picking one of the values and then possibly overriding it:
output = input
output = 0 if input < 0
But it’s a little confusing for the code to do something and then immediately say, “Wait! I didn’t mean that!†So there’s a compact version of if for just this purpose:
output = (input < 0) ? 0 : input
You can read that as “if input is less than zero, then return 0, else return whatever object input names.â€
This ?: construct is called either the question mark operator or, more question mark operator often, the ternary operator. (“Ternary†because it uses three expres- ternary operator sions, unlike operators such as +, which have two and are called binary operators.) binary operators
Most Viewed Articles (in Ruby ) |
Latest Articles (in Ruby) |
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Archived Comments
1. Errm, Rails is just a bunch of Ruby scripts, not a
View Tutorial By: gngn at 2010-07-12 22:19:55