やってみる

アウトプットすべく己を導くためのブログ。その試行錯誤すらたれ流す。

「Ruby プログラムの実行」を読む4(繰り返し while until)

 条件が真または偽ならループする。

成果物

情報源

繰り返し

while

 条件式が真のときブロック内の処理をくりかえす。

while 条件式 [do]
  式
end
while true
  p 'WHILE'
  break
end

 以下はcount += 1がないと無限ループになるので注意。

count = 0
while count < 5
  p "#{count}"
  count += 1
end

 breakで抜ける。

count = 0
while count < 5
  p "#{count}"
  count += 1
  break if count == 2
end

 nextで次のループへ飛ぶ。(C言語continue相当)

count = 0
while count < 5
  count += 1
  next if count == 2
  p "#{count}"
end

while修飾子

 処理と条件を短く書けるときに使う。

while 条件式

 コードで書いてみる。

break while true
count = 0
count+=1 while count < 5
class C
  def initialize; @count = 0; end
  def countup; @count += 1; end
  def loop?; @count < 5; end
  attr_reader :count
end
c = C.new
p c.count
c.countup while c.loop?
p c.count

until

 条件式が偽のときブロック内の処理をくりかえす。

until 条件式 [do]
  式
end
until false
  p 'UNTIL'
  break
end

 以下はcount += 1がないと無限ループになるので注意。

count = 0
until 5 < count
  p "#{count}"
  count += 1
end

 breakで抜ける。

count = 0
until 5 < count
  p "#{count}"
  count += 1
  break if count == 2
end

 nextで次のループへ飛ぶ。(C言語continue相当)

count = 0
until 5 < count
  count += 1
  next if count == 2
  p "#{count}"
end

until修飾子

 処理と条件を短く書けるときに使う。

until 条件式

 コードで書いてみる。

break until false
count = 0
count+=1 until 5 < count
class C
  def initialize; @count = 0; end
  def countup; @count += 1; end
  def break?; 5 < @count; end
  attr_reader :count
end
c = C.new
p c.count
c.countup until c.break?
p c.count

所感

 真偽の反転や1行でかける修飾子はうれしい。短く書きたいからね。

対象環境