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?

More than 1 year has passed since last update.

WEB開発をやり始めてみる(Ruby:繰り返し処理)

Last updated at Posted at 2022-10-16

やったこと

Rubyではいろんな繰り返し処理があるようなのでメモ的なもの
使い方みたいなのはまた覚えるとして、とりあえず書いていこう

最初から最後まで順番に繰り返しながら実行する

for文もあるけど、今回はやらない

numbers = [1,2,3,4,5]
numbers.each do |number|
    puts number
end

# 一行で書くこともできる
numbers.each { |number| puts number }

# 番号をつけてあげる
numbers.each.with.index(1) do |number , i|
    puts "No #{number} #{i}回目の処理" 
end

# チーム分け
lists= ["A", "B", "C", "D", "E", "F"]

list.shuffle!
team_a = []
team_b = []

lists.each.with_index do |user, i|
    if i.odd?
        team_a << user
    else
        team_b << user
    end
end

text = "チームA\n"
team_a.each.with_index(1) do |member, i|
    text += "No#{i}:#{member}さん\n"
end

text += "\nチームB\n"
team_b.each.with_index(1) do |member, i|
    text += "No#{i}:#{member}さん\n"
end

puts text

単純にn回数実行(出力)したい時

#全部やっていることは一緒書き方が違うだけ
5.times do
  puts 'Hello!'
end

5.times do |i|
  puts "#{i}: Hello!"
end

5.times { |i| puts "#{i}: Hello!" }

5.times { |i|
  puts "#{i}: Hello!" 
}

指定した条件が真である時処理を繰り返す

# 10になるまでカウントする
i = 0

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

指定した条件を1ずつ増減させながら実行する

10.upto(14){ |n| puts n}
10
11
12
13
14

14.downto(10){ |n| puts n}
14
13
12
11
10

指定した条件をn数増減させながら実行する

1.step(10,2){|n| puts n}
1
3
5
7
9

10.step(1,-2){|n| puts n}
10
8
6
4
2

loop break next

# 無限ループ
i = 0
loop do
  puts i
  i += 1
end

# 10になったらループ処理を止める(break)
j = 0
loop do
  puts j
  j += 1
  break if j == 10
end

#
numbers = [1, 2, 3, 4, 5]
numbers.each do |n|
  next if n % 2 == 0 #偶数は飛ばす(奇数のみ出力)
  next if n.even? #偶数は飛ばす(奇数のみ出力)
  next if n.odd? #奇数は飛ばす(偶数のみ出力)
  puts n
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?