Ruby体験記6 〜ループ

どうも。三十路です。

本日はこの本の内容のループのお勉強。

プログラミング学習シリーズ Ruby 1 はじめてのプログラミング

プログラミング学習シリーズ Ruby 1 はじめてのプログラミング

ループ

while

whileとは条件式が真を返す間はループを繰り返す

while 条件式
 処理
end

例)
aが10より小さい間ループする

while a<10
 a+=1
end

小問題2

computer = rand 6 + 1
plr_win = false

trial_count=0
LOOP = 3
while LOOP > trial_count && plr_win == false
  #choice = gets
  #eclipseではgets使えないので直接代入しておく取りあえず・・・
  choice = 3
  player = Integer choice
  
  if player == computer
    plr_win = true
  end
  
  trial_count += 1
end

if plr_win
  puts "win"
else
  puts "lose"
end
for

forとは開始と終了をしていして、その間繰り返すループ式。

例)

for i in 1..10
 処理
end

小問題3

str = "**********"
for i in 0..9
  puts str[0..i]
end
ループに関連する命令(他でも使うかもだけど?)

breakとはループから抜ける
returnは関数またはループから抜ける
nextは処理をスキップする

while i>100
  i+=1
  if i == 30
    break
  end
end
for i in 1..10
  if i % 2 == 0
    next
  end
  puts i
end

練習問題

(1)めんどいから飛ばす
(2)

puts "1 - 6?"
computer = rand 6 + 1
plr_win = false

for i in 0..3
  #choice = gets
  a = rand 6 + 1
  choice = "0123456"[a..a]
  player = Integer choice
  if player == computer
    plr_win = true
    break
  elsif player == computer+1 || player == computer-1
    puts "close"
  end
end

if plr_win
  puts "win"
else
  puts "lose"
end

(3)
1:x=1, y=1
2:x=1, y=1
3:x=8, y=2
4:x=1, y=1

そんな日。