$ python -c "print 1 if true else 2 if true else 3 if true else 4 if true else 5 "
1
$ node -e " true ? 1 : true ? 2 : true ? 3 : true ? 4 : 5 "
1
$ perl -e "print true ? 1 : true ? 2 : true ? 3 : true ? 4 : 5 "
1
$ ruby -e "print true ? 1 : true ? 2 : true ? 3 : true ? 4 : 5 "
1
$ php -r "print true ? 1 : true ? 2 : true ? 3 : true ? 4 : 5 ;"
4
Java and C ++ will also return 1 value = isCondFirst() ? valueFirst() : isCondSecond() ? valueSecond() : isCondThird() ? valueThird() : valueDefault(); /********** **********/ if (isCondFirst()) { value = valueFirst(); } else if (isCondSecond()) { value = valueSecond(); } else if (isCondThird()) { value = valueThird(); } else { value = valueDefault(); }
$ php -r "print true ? 1 : ( true ? 2 : ( true ? 3 : ( true ? 4 : 5 )));"
1
$foo = $lambda('fooMsg', 'fooReturn')
, $foo
contains a function that, when called, will output the message 'fooMsg'
to the console and return the value of 'fooReturn'
$ cat ternary. js
var lambda = function (logMsg, returnValue) { return function () { console.log(logMsg); return returnValue; }; }; var cond = { first : lambda('cond.first' , true), second: lambda('cond.second', true), third : lambda('cond.third' , true) }; var value = { first : lambda('value.first' , 'first'), second : lambda('value.second' , 'second'), third : lambda('value.third' , 'third'), default: lambda('value.default', 'default') }; console.log( 'result: ', cond.first() ? value.first() : cond.second() ? value.second() : cond.third() ? value.third() : value.default() );
$ node ternary. js
cond.first
value.first
result: first$ cat ternary. php
<?php $lambda = function ($logMsg, $returnValue) { return function () use ($logMsg, $returnValue) { echo $logMsg . PHP_EOL; return $returnValue; }; }; $cond = array( 'first' => $lambda('cond.first' , true), 'second'=> $lambda('cond.second', true), 'third' => $lambda('cond.third' , true), ); $value = array( 'first' => $lambda('value.first' , 'first'), 'second' => $lambda('value.second' , 'second'), 'third' => $lambda('value.third' , 'third'), 'default'=> $lambda('value.default', 'default'), ); echo 'result: ' . ( $cond['first']() ? $value['first']() : $cond['second']() ? $value['second']() : $cond['third']() ? $value['third']() : $value['default']() ) . PHP_EOL; ?>
$ php ternary. php
cond.first
value.first
value.second
value.third
result: third
(cond.first() ? value.first() : (cond.second() ? value.second() : (cond.third() ? value.third() : (value.default())))); /******** * ===> */ true ? 'value.first' : /* ignored */;
( ( cond.first() ? value.first() : cond.second() ) ? value.second() : cond.third() ) ? value.third() : value.default(); /******** * ===> */ ( ( 'value.first' ) ? value.second() : cond.third() ) ? value.third() : value.default(); /******** * ===> */ ( 'value.second' ) ? value.third() : value.default(); /******** * ===> */ 'value.third'
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
Source: https://habr.com/ru/post/114899/
All Articles