0
0

More than 3 years have passed since last update.

【Ruby】条件演算子が2回(以上)続く時

Last updated at Posted at 2020-06-12

※本文内容が誤っていたことをコメント欄で教えて頂いたので修正しました。

きっかけ

以前ある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" が残る。

参考

Rubyのしくみ Ruby Under a Microscope

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0