LoginSignup
0
1

More than 3 years have passed since last update.

ruby while、for、loop、break、nextについて

Posted at

while

 i = 0
 while i < 10 do
     puts "#{i}: hello" 
     i += 1
 end

※ 「i = i + 1」は「 i += 1 」と同様の意味

times

  • timesは数字オブジェクトのメソッド
10.times do |i|
puts "#{i}:hello"
end
  • do~endの中で繰り返したい処理を繰り返す
  • do の後で|i|を定義することでwhileの時と同じように何回ループしているかが分かる

上記のtimesは1行で書くことが出来る

10.times { |i|puts "10#{i}:hello" }

for文

  • doは省略出来る
 for i in 18..20 do
     p i
 end
 for color in ["red", "blue"] do
     p color
 end

 for name,score in {aratomai: 200, Mikkey: 500} do
     puts "#{name}: #{score}"
 end

実行結果:

  • 18
  • 19
  • 20
  • "red"
  • "blue"
  • aratomai: 200
  • Mikkey: 500

eachメソッドへの書き換え

 (18..20).each do |i|
     p i
 end
 ["red", "blue"].each do |color|
     p color
 end
 {aratomai: 200, Mikkey: 500}.each do |name, score|
     puts "#{name}: #{score}"
 end

実行結果:
上記と同じ

loop

  • breakしない限り永久ループ
i = 0
 loop do
     p i
     i += 1
     end

breakとnextについて

  • iが5になった時に処理が終わる
10.times do |i|
    if i == 5
        break
    end
    p i
end

実行結果:
0
1
2
3
4

  • iが5の時だけ処理をスキップする
10.times do |i|
    if i == 5
        next
    end
    p i
end

実行結果:
0
1
2
3
4
6
7
8
9

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