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?

do-whileステートメントのRubyでの書き方

Last updated at Posted at 2025-08-01

要約

よくC言語を書いていて、do-whileステートメントをRubyで書きたいと思えたことはないだろうか?Rubyはオブジェクト指向言語であるため、C言語のような関数手続きを書こうとしてもスタイルが合わない。そのため、Rubyの記法で考える必要が生じてくる。

do-whileステートメントについて

以下がdo-whileステートメントである。

do {
  // :
} while (); 

do-whileステートメントはwhileステートメントとは異なり必ず一度は読み込む。whileステートメントはこの振る舞いを持たず、条件が偽ならばループ文を読み込まない。

while () { // 条件を()の間に記述する
  // 初めから条件が真でないならば読み込みもループもしない
}

do-whileステートメントは一度読み込んでからループするかの判定を持つ。

do {
  // 条件は構わず処理する
} while ();  // ()内の条件が真ならば反復処理する

Rubyでの記述

Rubyではbegin-endステートメントとwhileステートメントのメソッドチェーンで実現できる。
beginステートメントとendステートメントの間が反復処理する内容、whileで条件を作る。

begin

end while ()

例を以下に示す。適当にバイト数を出して0x80未満ならば反復処理をするというプログラムである。

count = 0
begin
    byte = Random.bytes(1).unpack1('C')
    count = count.succ
end while byte < 0x80
p count

実行結果を以下に。

6
0
0
1

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?