1
1

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

【ruby】『ruby入門(メモ3)』恐竜判定(if ... elseとcase when)

Posted at

0.はじめに

今回は判定文(if,when)を勉強する。
参考urlの内容を少しだけアレンジ。
この子からパワーを貰って、勉強を進めている。

indominus_20200410.jpg

1.判定文(if else)

2つの条件について判定して、何かをさせたいとき下記のように記述できる

__ if 条件1__
__  条件1の時実行する処理__
__ else__
__  条件1以外の処理__
__ end__

2.判定文(3つ以上の条件について判定したいとき if elsif else)

3つ以上の条件について判定して、何かをさせたいとき下記のように記述できる

__ if 条件1__
__  条件1で実行したい処理__
__ elsif 条件2__
__  条件2で実行したい処理__
__ else__
__  条件1、2以外の時実行したい処理__
__ end__

複数条件判定(if elsif else)のサンプル

入力した数字で、ヴェロキラプトルかティラノサウルスかotherかを表示するプログラム。

if_else.rb
puts '---------which do you choose(104 or 132)----'
# 画面からの入力は、getsで受け取る
speed = gets.to_i
# speedが104のときは
if speed == 104
	puts 'Tyrannosaurus'
# speedが132のときは
elsif speed == 132
	puts 'Velociraptor'
# speedが132でも104でもないときは
else
	puts 'other dinosor'
end
★実行結果
c:\ruby_pg>ruby if_else.rb
---------which do you choose(104 or 132)----
132
Velociraptor

3.判定文3つ以上の条件について判定したいとき(case when else)

3つ以上の状態を持つものについて判定したいとき、
if elsif elseを使うより下記のようにcase whenを使うと効率のいい場合がある。

__ case 判定対象__
__ when 条件1__
__  条件1でき実行したい処理__
__ when 条件2__
__  条件2で実行したい処理__
__  ...__
__ else__
__  いずれの条件にも該当しない時にで実行したい処理__
__ end__

★★好きな恐竜を表す番号を入力すると、その恐竜名を表示するサンプルプログラム

if_else.rb
# 略
puts "\n"
puts '-------what dinosor do you like? --------'
puts 'input 1 if you like Tyrannosaurus --------'
puts 'input 2 if you like Velociraptor --------'
puts 'input 3 if you like Stegosaurus --------'
puts 'input 4 if you like Triceratops --------'
puts 'input 5 if you like Brachiosaurus --------'

# 画面からの入力は、getsで受け取る
dino_no = gets.to_i
# dino_noの場合分け
case dino_no
# 1の場合
when 1
	puts 'you like Tyrannosaurus'
# 2の場合
when 2
	puts 'you like Velociraptor'
# 3の場合
when 3
	puts 'you like Stegosaurus'
# 4の場合
when 4
	puts 'you like Triceratops'
# 5の場合
when 5
	puts 'you like Brachiosaurus'
# 他の場合
else
	puts 'you like ???'
end

実行結果

c:\ruby_pg>ruby if_else.rb

-------what dinosor do you like? --------
input 1 if you like Tyrannosaurus --------
input 2 if you like Velociraptor --------
input 3 if you like Stegosaurus --------
input 4 if you like Triceratops --------
input 5 if you like Brachiosaurus --------
3
you like Stegosaurus

参考url

dotinstall(ruby入門)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?