繰り返し
while
=begin
繰り返し
=end
# 初期値
i = 1
# 条件が真の場合は繰り返す
while i < 10 do
print("#{i}-test-while\n")
i += 1
end
while修飾子
=begin
繰り返し(while)
=end
# 開始値
i = 10;
# 出力
print("#{i}-test\n")
# 処理の繰り返し
# 1行のみしか記述できないので注意
i = i - 1 while i > 1 # 条件が真の場合に左辺の処理を繰り返す
# 出力
print("#{i}-test\n")
until
=begin
繰り返し(until)1
=end
# 初期値設定
i = 1;
# 条件が真になるまで繰り返す
until i > 10 do
print("#{i}-test\n")
i = i + 1
end
until修飾子
=begin
繰り返し(until修飾子)2
=end
# 初期値
i = 1
# 出力
print("#{i}-test\n")
# 繰り返し
i = i + 1 until i >= 10 # 1文しか指定できないので複数の処理を実行した場合はメソッドを使用
# 出力
print("#{i}-test\n")
for
=begin
繰り返し(for)
=end
# 配列内のものを出力
array = [10, 20, 30]
for i in array do
print("#{i}-test-for\n")
end
print("\n")
# 範囲演算子を指定
for i in 1 .. 10 do
print("#{i}-test-for2\n")
end
print("\n")
# 配列を出力
array = [40, 50, 60]
array.each do |i|
puts i
end
break、next、redo
=begin
繰り返し制御
break
=end
i = 1
j = 1
while i < 10 do
# 処理をスキップ(next)
if i == 2 then
i = i + 1
# 先頭へ戻る
next
end
# 処理を繰り返す(redo)
if j == 1 then
i = i + 1
j = 2
# 処理を繰り返す
redo
end
# 処理を抜ける(break)
if i > 5 then
# ループ処理処理脱出
break
end
print("#{i}-break\n")
i = i + 1
end
最終更新:2011年04月23日 21:03