9
10

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.

rubyの代入演算子 ||

Last updated at Posted at 2016-07-07

github上の他人のコードを見ていると 『a = || b』や『a = || b』といったコードが割と頻繁に出てきて、出てくるたびに調べるけどすぐ忘れるといったことが何回か続いたので忘れないようにメモしておこうと思う。

『a = a || b』の場合、『a = a || b』が実行されるたびに変数 a に値が格納される。
他方、『a ||= b』は、a が nil か false の場合だけ、変数 a に値が格納される。

#下記の二行はほぼ同じ振る舞い
a ||= 100
a || a = 100
9
10
3

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
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?