0
0

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 3 years have passed since last update.

Ruby case文についてまとめてみた

Last updated at Posted at 2021-04-01

case文とは?

「if」文では複数の条件式を組み合わせて複雑な分岐を行う事ができますが、一つの値に対して複数の候補の中で一致するものを探すような場合には「case」文を使用すると便利です。

下記は
ハイフン付きの電話番号が与えられたとき、その電話番号を入力し終えるまでに「ダイヤルが回る必要のある総距離を計算するプログラム」となってます。
例えば、 9315-35-7398 という電話番号であれば、 9 を入力するために 11+11=22 、 次に 3 を入力するために 5+5=10 、 ... となり合計で距離 22+10+...=146 だけダイヤルが回ります。

スクリーンショット 2021-04-02 9.25.12.png


number = [9315-35-7398]
number1 = number.delete("-").chars.map(&:to_i)
total = 0

number1.each do |n|
  case n
      when 0
        n = 12
      when 1
        n = 3
      when 2
        n = 4
      when 3
        n = 5
      when 4
        n = 6
      when 5
        n = 7
      when 6
        n = 8
      when 7
        n = 9
      when 8
        n = 10
      when 9
        n = 11
      else
      end
 total += n * 2
end

puts total


=> 146

caseに指定した「対象」がwhenに指定した条件のどれかに当てはまる場合、それにあてはまった処理を実行します。
もしどれにも当てはまらない場合は、elseにある処理が実行される流れとなります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?