※本文内容が誤っていたことをコメント欄で教えて頂いたので修正しました。
きっかけ
以前あるgemのインストールに失敗してしまった時に原因を探っていて、以下のコードにたどり着いたのだが、1行に条件演算子が2回出てきて「これはどういう条件で動くんだ?」と分からなかったのでメモ。
idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []
結論
外側から内側に向かって、順繰りに評価されていく。
irb
> 1 == 1 ? 2 == 2 ? "a" : "b" : "c"
=> "a"
# 1 == 1 が true なので 「"a" : "b"」 と : "c" とで 「"a" : "b"」, 次に 2 == 2 が true なので "a" : "b" は "a"
> 1 == 1 ? 2 == 0 ? 3 == 3 ? "a" : "b" : "c" : "d"
=> "c"
> 1 == 0 ? 2 == 0 ? 3 == 3 ? "a" : "b" : "c" : "d"
=> "d"
確認したこと
ドキュメントがぱっと見つからなかったので、構文解析をしてみることにした。Ripperでも見てみたけど、初心者にはparserが見やすかった。
console
% ruby-parse -e 'puts 1 == 1 ? 2 == 2 ? "a" : "b" : "c"'
(send nil :puts
(if
(send
(int 1) :==
(int 1))
(if
(send
(int 2) :==
(int 2))
(str "a")
(str "b"))
(str "c")))
パースした結果をみてみると、どうやら最初に内側の 1 == 1
が評価され、その結果が "a" : "b"
: "c"
にかかって"a" : "b"
が残る。その結果を持って、次に 1 == 1
の評価にすすみ、先程残った "a" : "b"
に対して "a"
が残る。