90
78

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.

&&とandの違い

Last updated at Posted at 2013-06-28

優先度が違う

Ruby 2.0.0 リファレンスマニュアル > spec/operator
演算子式
まず、左辺を評価して、結果が真であった場合には右辺も評価しま す。and は同じ働きをする優先順位の低い演算子です。
and を伴う式をメソッドの引数に渡す場合は二重に括弧が必要となります。

pry
2.0.0 (main)>a = true && false
2.0.0 (main)>a
#=> false

2.0.0 (main)>b = true and false
2.0.0 (main)>b
#=> true
# ( b = true ) && false 

2.0.0 (main)>c = (true and false)
2.0.0 (main)>c
#=> false

render foo and returnとかの場合以外は&&を使うようにしています。


追記: 2013-07-16

以下のような状況で注意

pry-edit
if true and false
  puts "1: true"
else
  puts "1: false"
end
#=> 1: false


true_and_false = true and false
if true_and_false
  puts "2: true"
else
  puts "2: false"
end
#=> 2: true

追記: 2013-08-06

Contributing to Ruby on Rails — Ruby on Rails Guides

  • Prefer &&/|| over and/or.

どっかで見たなーと思ったら、Rails Guidesに記述がありました。

実録!Railsのはまりポイント10選
http://www.slideshare.net/drecom/edgerails2

ここにも出てきますね。

90
78
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
90
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?