Ruby 2.1の基本構文/基本文法まとめ&Pryの使い方若手エンジニア/初心者のためのRuby 2.1入門(2)(6/7 ページ)

» 2014年03月27日 18時00分 公開
[著:麻田優真、監修:山根剛司,株式会社アジャイルウェア]

while

基本形

 whileは、条件式が真の間、処理を繰り返すために使います。sample11.rbに、1から10までカウントアップする例を示します。ループ中で変数「i」を1ずつ増やしながら、「i」が10に達したらループを脱出します。

i = 1
while i <= 10
  puts i
  i += 1
end
sample11.rb
$ ruby sample11.rb
1
2
3
4
5
6
7
8
9
10
sample11.rbの実行結果

後置のwhile

 ifやunlessと同様、後置することもできます。sample12.rbは後置whileを利用して変数「i」をカウントアップする例です。「i」が10の場合にも「i += 1」が実行されるため、結果として11が出力されています。

i = 1
i += 1 while i <= 10
puts i
sample12.rb
$ ruby sample12.rb
11
sample12.rbの実行結果

break

 breakを使うとループを脱出できます。恣意的な例ですが、sample11.rbをbreakを使って書き換えた例をsample13.rbに示します。whileの条件式にtrueを与えて無限ループを作り、breakとifを用いてループを脱出しています。

i = 1
while true
  puts i
  i += 1
  break if i > 10
end
sample13.rb
$ ruby sample13.rb
1
2
3
4
5
6
7
8
9
10
sample13.rbの実行結果

next

 nextを使うと、以降の処理をスキップして次のループに移ることができます。sample14.rbは、1から10まで、3の倍数以外の値を出力しながらカウントアップする例です。

i = 0
while i < 10
  i += 1
  next if i % 3 == 0
  puts i
end
sample14.rb
$ ruby sample14.rb
1
2
4
5
7
8
10
sample14.rbの出力結果

 なおbreakやnextは、以降で説明するuntilforでも用いることができます。

until

 untilはwhileとは逆に、条件式が偽の間、繰り返し処理を行うために使います。whileと同様に後置することも可能です。sample15.rbは、sample11.rbをuntilを用いて書き換えたものです。

i = 1
until i > 10
  puts i
  i += 1
end
sample15.rb
$ ruby sample15.rb
1
2
3
4
5
6
7
8
9
10
sample15.rbの実行結果

Copyright © ITmedia, Inc. All Rights Reserved.

RSSについて

アイティメディアIDについて

メールマガジン登録

@ITのメールマガジンは、 もちろん、すべて無料です。ぜひメールマガジンをご購読ください。