1
1

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 3 years have passed since last update.

rubyの気づきにくい代入 やばい or and

Last updated at Posted at 2020-04-18

問題

単純にandorを代入で使うと死ぬ

x = false or true # => true なのに ...
p x # => false !!!!

x = true or false # => true
p x # => true
x = false and true # => false
p x # => false 

x = true and false # => false なのに ...
p x # => true !!!!

なぜか

andor=より優先順位が低い
演算子式__Ruby_2_7_0_リファレンスマニュアル_-2.png

x = false or true
# は (x = false) or true と解釈されるので ...

回避方法

x = (false or true)
x = false || true

x = (false and true)
x = false && true
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?