109
96

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 on Rails] 複数の条件で条件分岐したい時の書き方4種

Last updated at Posted at 2016-11-30

Overview

Rubyで1つの値に対して複数の条件で条件分岐させたい時の記述方法メモです。
自分はデザイナー職なのでhtmlのクラス名の出し分けで使ったりすることが多く、ワンライナーで書ける3のinを使う方法が好み。

1: or を使う

単純にorで繋げた原始的なやりかた。

if name == 'kaoru' || name == 'nana' || name == 'ryoko'
  処理A
else
  処理B
end

2: case文 を使う

case文ならwhenで引数を複数渡せるので、複数条件が複数あるときの分岐はこれが便利か。三項演算子でワンライナーでいけないのが欠点。

case name
when 'kaoru','nana','ryoko'
  処理A
else
  処理B
end

3: in? を使う

ActiveSupport のinを使う。ワンライナーでも書きやすいし可読性が良い。
ソース http://api.rubyonrails.org/classes/Object.html#method-i-in-3F

if name.in?(['kaoru','nana','ryoko'])
  処理A
else
  処理B
end
三項演算子ver.
name.in?(['kaoru','nana','ryoko'])? 処理A : 処理B

4 include? を使う

3同様ワンライナーで書きやすい。
けど値が最初にきてわかりづらいから3のほうが個人的にはすき。

if ['kaoru','nana','ryoko'].include?(name)
  処理A
else
  処理B
end
三項演算子ver.
['kaoru','nana','ryoko'].include?(name)? 処理A : 処理B
109
96
4

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
109
96

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?