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

備忘録(そのほかの条件分岐、繰り返し処理)

0
Last updated at Posted at 2021-01-03

if文以外の条件分岐

case文

複数の条件を指定する時に、if文のelsifを重ねるよりもcase文を使用した方がシンプルにコードを書くことができる

例)if文

country = "Japan"

if country == "Japan"
 puts "こんにちは"
elsif  country == "America"
 puts "Hello"
elsif  country == "France"
 puts "Bonjour"
elsif  country == "China"
 puts "你好"
elsif  country == "Italy"
 puts "Buon giorno"
elsif  country == "Germany"
 puts "Guten Tag"
else
 puts "..."
end

例)case文

country = "Japan"

case country
when "Japan"
 puts "こんにちは"
when "America"
 puts "Hello"
when "France"
 puts "Bonjour"
when "China"
 puts "你好"
when "Italy"
 puts "Buon giorno"
when "Germany"
 puts "Guten Tag"
else
 puts "..."
end

条件つきの繰り返し処理

while文

繰り返し処理を行うためのRubyの構文
指定した条件が真である間、処理を繰り返す

例)

number = 0

while number <= 10
 puts number
 number += 1
# 10になるまで処理が繰り返される
end

無限ループ

処理が永遠に繰り返されること
上の例のnumber += 1を削除した場合無限に0が出力されてしまう
ループから抜け出すにはbreakを使用する

number = 0

while number <= 10
 if number == 5
   break
# 特定の条件になったらループを脱出できる
 end
 puts number
 number += 1
end
0
0
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
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?