- 1. case
1. case
case に関しての詳細は「Ruby 2.5.0 リファレンスマニュアル > 制御構造 - case」でどうぞ。
いわゆる C言語でいうところの switch ~ case とは趣がいささか異なるので注意が必要です。
C言語を知らない人には申し訳ないが、C言語で。
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char input[PATH_MAX] = {};
printf("なんか数値を入力してちょ ");
fgets(input, sizeof(input), stdin);
switch(atoi(input))
{
case 1:
printf("1 だぎゃ\n");
break;
case 2:
case 3:
case 4:
printf("2~4 のどれかだぎゃ\n");
break;
case 5:
case 7:
printf("5 か 7 だぎゃ\n");
break;
default:
printf("1~5 と 7 以外だぎゃ\n");
break;
}
return 0;
}
と書いているものと Ruby で。
#!/usr/bin/env ruby
print('なんか数値を入力してちょ ')
input = gets
case input.to_i
when 1
puts('1 だぎゃ')
when 2 .. 4
puts('2~4 のどれかだぎゃ')
when 5,7
puts('5 か 7 だぎゃ')
else
puts('1~5 と 7 以外だぎゃ')
end
と書いているのはまったく同じ動きをします。
9行目の記述は、使いようのある場面では便利かもしれません。「..」の前後には空白を空けないといけないのでご注意を。
|
    |