[Ruby] When the conditional operator continues twice (or more)

Trigger

When I failed to install a gem before, I was searching for the cause and arrived at the following code, but the conditional operator appeared twice on one line and asked "Under what conditions does this work?" I didn't understand, so make a note.

idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []

https://github.com/ruby/ruby/blob/master/lib/mkmf.rb#L1780

Conclusion

It is evaluated in order from the outside to the inside.

irb


> 1 == 1 ? 2 == 2 ? "a" : "b" : "c"
=> "a"
# 1 ==Since 1 is true, ""a" : "b"" When: "c"And ""a" : "b"」,Then 2==Because 2 is true"a" : "b"Is"a"

> 1 == 1 ? 2 == 0 ? 3 == 3 ? "a" : "b" : "c" : "d"
=> "c"

> 1 == 0 ? 2 == 0 ? 3 == 3 ? "a" : "b" : "c" : "d"
=> "d"

What I confirmed

I couldn't find the documentation at once, so I decided to parse it. I also looked at Ripper, but parser was easy for beginners to see.

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")))

Looking at the parsed result, it seems that the inner 1 == 1 is evaluated first, and the result depends on"a": "b": "c" ``" a ":" b " remains. With the result, we proceed to the evaluation of 1 == 1, and"a"remains for the remaining"a": "b".

reference

<a target="_blank" href="https://www.amazon.co.jp/gp/product/B01IGW56CU/ref=as_li_tl?ie=UTF8&camp=247&creative=1211&creativeASIN=B01IGW56CU&linkCode=as2&tag=kuredev-22&linkId=10c75e8a70a2107a > How Ruby works Ruby Under a Microscope

Recommended Posts

[Ruby] When the conditional operator continues twice (or more)
About the [ruby] operator
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
When the Ruby on Rails terminal rolls back