Ternary Operators – Three is magic
Binary’s Sibling Ternary
The ternary operator for many programming languages allows you to use a shorthand when making simple evaluations. The usual sequence of conditions (and this can vary between languages, so search for ‘your_language ternary operator‘ for more information.) Using this operator allows us to take ~6 lines of code and replace it with one line of code. In general this is best used selectively and for simple conditions, otherwise use the extra lines of code (regardless of language) so who-ever-has-to-support-your-code will remain sane…
if boolean_condition_matches then do_first_thing else do_something_different end
Note that the code structure requirements will vary between languages so you may need brackets, braces, etc. for your target language. BTW – most *NIX shells do not directly support the ternary operator…
Simple examples [Boolean | result_if_true | result_if_false]
- economy = price_of_gas > $2 ? “Bad” : “Hmmm” ### set the value of the variable ‘economy‘ to ‘Bad’ or ‘Hmmm’
- max_lines > 20? max_lines = 0 : max_lines++ ### increment or reset the variable ‘max_lines‘
Ruby:
- boolean? ? do_first_thing : do_something_different
- lets_party = (year > 2012) ? “Party-TIME!” : “Are_You_Ready?”
Ruby IRB Session example:
irb(main):005:0> year=2010 => 2010 irb(main):006:0> lets_party = (year > 2012) ? "Party-TIME!" : "Are_You_Ready?" => "Are_You_Ready?" irb(main):007:0> year=2013 => 2013 irb(main):008:0> lets_party = (year > 2012) ? "Party-TIME!" : "Are_You_Ready?" => "Party-TIME!"
Javascript
<script language=javascript>
var b=5;
(b == 5) ? a="true" : a="false"; ### Ternary operator
document.write("Result: "+a);
</script>
Result: true ### the output in this example
PHP (from php.net)
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : 'false') ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?> Related posts:
- Automating Standard Script Generation Some thoughts on Automating and standardizing how you might create...
- From Bash to Ruby – part 1 Bash - Changing from a proven, ubiquitous tool to a...
- Migrating Static HTML pages to Wordpress CMS I previously posted about migrating static pages to Drupal –...
- Zena – Rails CMS & VDI Playground CMS=Content Management System Rails = Ruby on Rails – a...
- Rails – where is the missing stuff? ROR (Ruby on Rails) is advertised as a data-centric development...