Skip to main content

三項演算子(3項演算子、TernaryOperator).入れ子

Python

py
rank = 'F' if x < 40 \
else 'C' if x < 50 \
else 'B' if x < 75 \
else 'A' if x < 90 \
else 'S'

PHP

php
$rank = ($x < 40 ? 'F'
: ($x < 50 ? 'C'
: ($x < 75 ? 'B'
: ($x < 90 ? 'A'
: 'S'))));

以前のバージョンで変な動作になるなと思ってたら、 最近のバージョンはカッコをつけないとエラーになってくれる。

txt
Unparenthesized `a ? b : c ? d : e` is not supported.
Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)`

Ruby

rb
rank = x < 40 ? 'F'
: x < 50 ? 'C'
: x < 75 ? 'B'
: x < 90 ? 'A'
: 'S'