繰り返し文にいくつか方法があったのでメモします。
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
【結果】
=> 大吉が出続けるまでおみくじを引き続けるプログラム