By: Brian Marick in Ruby Tutorials on 2008年10月17日 [フレーム]
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
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
Most Viewed Articles (in Ruby )
Open and manipulate CSV files in Ruby
dRuby client/server mode sample program
Using Proxy to connect to URLs in Ruby
Reading URL content using Ruby (HTTP)
Latest Articles (in Ruby)
© 2023 Java-samples.com
Tutorial Archive: Data Science React Native Android AJAX ASP.net C C++ C# Cocoa Cloud Computing EJB Errors Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP Python Ruby SAP VB.net EJB Struts Trends WebServices XML Office 365 Hibernate
Latest Tutorials on: Data Science React Native Android AJAX ASP.net C Cocoa C++ C# EJB Errors Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP Python Ruby SAP VB.net EJB Struts Cloud Computing WebServices XML Office 365 Hibernate