LoginSignup
45
39

More than 5 years have passed since last update.

Ruby の case 文

Last updated at Posted at 2014-09-12

case 文、よく使いますよね。
case 文では when で指定した値に一致するかどうかを「===」演算子を使って比較しています。

case文
case name
when 'Andy'
  p 'Are you Andy?'
when 'Bob'
  p 'Are you Bob?'
else
  p 'Who are you?'
end

if 文に直すとこんな感じです。

if文
if 'Andy' === name
  p 'Are you Andy?'
elsif 'Bob' === name
  p 'Are you Bob?'
else
  p 'Who are you?'
end

「===」は左辺が数値や文字列の場合は「==」として、正規表現の場合は「=~」として、Range の場合は include? として(?) include?/member? として 比較してくれます。
そのことが case 文の柔軟性を生んでいるんですね。

case文(正規表現)
case name
when /Andy|Bob/
  p "Are you #{name}?"
else
  p 'Who are you?'
end
case文(範囲)
case age
when 0..12
  p 'You are a child.'
when 13..19
  p 'You are a teen-ager.'
else
  p 'You are an adult.'
end

case 文で意識することはないですが、「===」は結果を true/false で、「=~」は結果をマッチした位置(インデックス)で返すという違いはあるので、合わせて把握しておきましょう。

45
39
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
45
39