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

論理演算子「&& 」と 「||」

Posted at

&& 演算子と || 演算子の違いは右辺が実行されるかどうからしいです!

|| 演算子

左辺が true の場合、右辺は実行しない。
左辺が false の場合は、右辺は実行する。

&& 演算子

左辺が true の場合、右辺は実行する。
左辺が false の場合は、右辺は実行しない。

例題

a1 = [1, 3, 4]
a2 = [3, 4, 6]

p a1 && a2

上記のコードの場合、

  1. a1 は [1, 3, 4] → truthy(真とみなされる)
  2. a2 は [3, 4, 6] → これも truthy

Ruby では nil と false 以外はすべて「真(truthy)」らしい。
だから、配列同士でも && は「中身の比較」ではなく「真偽の評価」になる。

&& の評価ルール

Ruby の && は
左の式を評価 → 偽ならそれを返す
真なら右の式を評価してその値を返す

今回の場合
・左の a1 は真なので、右の a2 が評価されて返る
→ 結果は a2

[3, 4, 6]
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?