4
2

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のcase文で配列に特定の値が含まれているかチェックする方法

Posted at

配列に特定の値が含まれているかcase文で検証したい

case [1, 3, 5]
when "1が含まれる場合"
when "2が含まれる場合"
when "3が含まれる場合"

if文で書くなら簡単

return hoge1 if [1, 3, 5].include?(1)
return hoge2 if [1, 3, 5].include?(2)
return hoge3 if [1, 3, 5].include?(3)
return hoge4 if [1, 3, 5].include?(4)

パターン1: procにして比較する(シンプル)

case num_array
when 1.method(:in?).to_proc then :a
when 2.method(:in?).to_proc then :b
when 3.method(:in?).to_proc then :c
when 4.method(:in?).to_proc then :d
when 5.method(:in?).to_proc then :e
when 6.method(:in?).to_proc then :f
when 7.method(:in?).to_proc then :g
else :d
end

to_procする事でそのメソッドの実行結果で評価してくれる。

[1] pry(main)> 1.method(:in?)
=> #<Method: Integer(Object)#in?>

[2] pry(main)> 1.method(:in?).to_proc
=> #<Proc:0x000055b9fbdc7c50 (lambda)>

パターン2: ラムダを使って実装する

case num_array
  when included(1) then :a
  when included(2) then :b
  when included(3) then :c
  when included(4) then :d
  when included(5) then :e
  when included(6) then :f
  when included(7) then :g
  else :d
end


# ラムダ式を定義 num_array に num が含まれているかチェック
def included(num)
  ->num_array{num_array.include?(num)}
end

パターン3:lambda直書きversion

case num_array
when ->(ids) { 1.in?(ids) } then :a
when ->(ids) { 2.in?(ids) } then :b
when ->(ids) { 3.in?(ids) } then :c
when ->(ids) { 4.in?(ids) } then :d
when ->(ids) { 5.in?(ids) } then :e
when ->(ids) { 6.in?(ids) } then :f
when ->(ids) { 7.in?(ids) } then :g
else :d
end
4
2
3

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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?