LoginSignup
5

More than 5 years have passed since last update.

rubyで繰り返し処理を行う(while,times,for,each)

Last updated at Posted at 2017-07-29

繰り返しの処理

何回か同じ処理を繰り返したい時に

  • while
  • times
  • for
  • each

を使うと便利です。

  • while
  • times

は回数を指定して使いたい場合。例えば〜回処理をするなどの時に便利。

  • for
  • each

は配列などを参照して、要素がある分だけ繰り返し処理を行いたい場合便利です。

while書き方

test

i = 0

while i <10 do

puts "#{i}:hello"
i += 1

end

  • whileの条件分に入れている変数はwhile内で使える。
  • forとwhileは制御構造のため
    • doは省略可
    • スコープを作らない

times書き方

test

10.times do |i|

puts "#{i}:hello"

end

  • 10が繰り返す回数
  • iはtimes内で変数として使いたい時に設定

for書き方

test

for i in 15..20 do

  p i

end

for 変数 in 範囲 do

  p i

end

# 変数がinの範囲内で何回も処理を行う。timesなどと違い、変数がinの範囲内に変化する。

for colors in ["red","white"] do

  p colors

end

each書き方

test

colors = ["red","white"]

colors.each do |i|

 puts i

end

# 下記でも記入可能

["red","white"].each do |i|

 puts i

end

注意点

  • times や each はメソッドのためdo〜end でブロックをなす

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
5