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?

Rubyの基本(制御構造)

Posted at

if文による条件分岐

下記の例の「sample②」のように、実行したい処理を前に、条件を後に書くことも可能。
簡単な条件の処理であれば②の方がよりシンプルに書くことができる。

sample_01.rb
score = gets.to_i

# sample①
if score >= 90
    puts "A"
end

# sample②
puts "A" if score >= 90

case文による条件分岐

数値の条件は「>」などの記号だけでなく、「..」で指定することも可能。

sample_02.rb
score = gets.to_i

case score
when 90..100
  puts "A"
when 70..89
  puts "B"
else
  puts "C"
end

for文による条件分岐

繰り返す回数が決まっている場合はfor文が使える。
forの後に書く変数(「i」でなくても良い)はスコープ内で使用できる。

sample_03.rb
# 「Hello」を3回表示
for i in 1..3
  puts "Hello"
end

# 九九の9の段の答えを表示
for num in 1..9
  puts 9 * num
end
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?