条件が真または偽ならループする。
成果物
情報源
繰り返し
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行でかける修飾子はうれしい。短く書きたいからね。
対象環境
- Raspbierry pi 4 Model B
- Raspberry Pi OS buster 10.0 2020-08-20 ※
- bash 5.0.3(1)-release
- Ruby 3.0.2