10
11

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】=と==、&と&&、|と||の違い

Posted at

RubySilverの勉強でつまづいたのでメモします。

#=と==の違い

=が左辺に代入
==が同じ
です。

example.html.slim
- dinner = @dinner.vegetables? ? "食べたくない" : "食べる"
= dinner
example.rb
def hoge
  return false if @dinner.vegetables == "きゅうり"
  return false if @dinner.vegetables == "レタス"
  return false if @dinner.vegetables == "なす"

  true
end

#&と&&の違い

&が積集合(共通する要素を取り出す)
&&がtrue/falseを返す(全部true(存在する)ならtrue出力)
です。

a = [1, 2, 3]
b = [2, 3, 4]

# 共通する要素を出力
a & b
=> [2, 3]

# 最後に評価されたb(true)を出力
a && b
=> [1, 2, 3]

# aが偽のためnil(右辺を見ない)
a = nil

a && b
=> nil

#|と||の違い

・|が和集合
・||がtrue/falseを返す(true(存在する)の時点でtrue出力)
です。

a = [1, 2, 3]
b = [2, 3, 4]

# いずれかに含まれる要素を出力
a | b
=> [1, 2, 3, 4]

# 最初に評価されたa(true)を出力
a || b
=> [1, 2, 3]

# aが偽のためbを出力(右辺まで見る)
a = nil

a || b
=> [2, 3, 4]
10
11
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?