1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

真偽値と条件分岐についてまとめる!

Last updated at Posted at 2019-06-26

&&、||の返り値と評価を終了するタイミング

&&や||を使用した場合、式全体の返り値は必ずしもtrueやfalseになるとは限りません!

Rubyでは、式全体が真または偽であることが決定するまでは左辺から順に式を評価します!
式全体の真または偽が確定すると、式の評価が終了し、最後に評価した式の値を返します

言葉だけでは分かりにくいと思うで、コードを見て見ましょう!

smaple.rb
10 && 100 && 1000  #=> 1000
false && 100 && 1000 #=> false
10 && nil && 1000  #=> nil

nil || false #=> false
false || nil || 10 || 100 #=> 10

説明していきます!

10 & 100 & 1000であれば、全ての式を評価する必要があったため、最後の条件式である1000が返り値になっています!
一方で、false & 100 & 1000は1つ目のfalseを評価した時点で式全体の真偽値が偽であることが確定したため、そこで評価を終了し、falseを返しています!

||の場合も考え方は同じです!
false || nil || 10 || 100の返り値が10になるのは、10を評価した時点で式全体の真偽値が真であることが確定したからです!


Rubyにおいては、if文以外でも&&や||を使うことが多いので、そのような時にこのような仕組みを理解しておくと便利だと思います!

ご静聴ありがとうございました!

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?