LoginSignup
25
23

More than 5 years have passed since last update.

Ruby の case 文で,値が配列に含まれているかを調べる

Posted at

ある値 num が配列 ary1 に含まれているとき,配列 ary2 に含まれているとき,それ以外のときで処理を分岐させたいときは,配列の前に '*' を前置して配列を展開することで実現できる.

num = 4
ary1 = [1, 2, 3]
ary2 = [4, 5, 6]

case num
when *ary1
  puts 1
when *ary2
  puts 2
else
  puts 3
end

# >> 2
25
23
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
25
23