Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
77
Help us understand the problem. What is going on with this article?
@fukayatsu

&&とandの違い

More than 5 years have passed since last update.

優先度が違う

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

ここにも出てきますね。

77
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
fukayatsu
(\\( ⁰⊖⁰)/)
esaLLC
esa.io や pplog.net などのWebサービスを開発・デザイン・運営しています

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
77
Help us understand the problem. What is going on with this article?