条件分岐で書き漏らしがあった。
case文というものが条件分岐で使える。
C系の言語でいうところのswitch文を少し強力にしたようなものになる。
簡単に書き方と動きを見てみる。
書き方自体は、Cとかのswitch文と同じような形になってる。
case 式1
when 式2(必要に応じてカンマ区切りで書ける)
# 式2 === 式1がtrueのときに実行
when 式3
# 式3 === 式1がtrueのときに実行
else
# どのwhen句にも入らないときに実行
end
==ではなく===演算子で評価しているのが特徴的だ。
この===演算子は、正規表現 === 文字列だと正規表現にマッチするかどうか、範囲 === 値だと値が範囲内にあるかどうかとかいい感じに評価してくれる。文字列 === 文字列だと普通の比較になる。
ちょっと試してみよう。
i = 10
case i
when 10
puts "10です"
when 20
puts "20です"
else
puts "その他です"
end
これを実行するとiが10になっているので、when 10の部分が実行される。その結果「10です」とコンソールに表示される。
iを20にするとwhen 20の部分が実行され、iが10でも20でもないと「その他です」と表示される。
カンマで複数の式を指定したり、単純な一致ではなくて、正規表現を使った場合もいける。
# iの値が10か20の時と、30か40の時と、その他の時で表示されるメッセージが変わる
i = 10
case i
when 10, 20
puts "10か20です"
when 30, 40
puts "30か40です"
else
puts "その他です"
end
# strの値が郵便番号か電話番号のフォーマットに一致する時と、その他の時で表示されるメッセージが変わる
str = "000-0000-0000"
case str
when /^\d{3}-\d{4}$/, # 郵便番号
/^\d{3}-\d{4}-\d{4}$/ # 携帯電話番号
puts "郵便番号か携帯電話番号"
else
puts "よくわからない"
end
最後に、case文も戻り値があるのでa = case 10 .... endみたいに書くことが出来る。
# iが10か20の時と、30か40の時と、その他の時でjの値が変わる。
i = 10
j = case i
when 10, 20
"10か20"
when 30, 40
"30か40"
else
"よくわからん"
end
# iの値に応じて、10か20, 30か40, よくわからんのどれかが表示される
puts j