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 5 years have passed since last update.

【Ruby入門】 繰り返し文

Last updated at Posted at 2019-09-10

繰り返し文にいくつか方法があったのでメモします。

1.each

words = ["aaa", "iii", "uuu"]

words.each do |word|
     puts word
end

【結果】
aaa
iii
uuu

2.times do

omikuji = ["大吉", "中吉", "凶"]
3.times do |num|
    puts omikuji[num]
end

【結果】
大吉
中吉

||はブロック変数で、
doからendの中でしか使えないもの。
普通の変数と同じように、名前を自由につけることができる。

omikuji = ["大吉", "中吉", "凶"]
3.times do
    puts omikuji.sample
end

【結果】
中吉
大吉
中吉
(=> ランダムに3回表示される)

3.while

a = 0
while(a < 100)
    puts a
    a += 10
end

【結果】
0
10
20
30
40
50
60
70
80
90

omikuji = ["大吉", "中吉", "凶"]

result = omikuji.sample
while(result != "大吉")
    puts result
    result = omikuji.sample
end
puts result

【結果】
=> 大吉が出続けるまでおみくじを引き続けるプログラム

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?