LoginSignup
5
2

More than 5 years have passed since last update.

Rubyの無限ループでループカウンタを使う

Last updated at Posted at 2016-12-27

Rubyで無限ループは以下のように書ける。

loop do
  puts "無限ループって怖くね?"
end

しかし、この方法だとループカウンタが使えない。

以下のように、loop_with_indexメソッドをKernelモジュールに定義することで、
あたかも構文のようにループカウンタ付きの無限ループが記述できる。
(標準的なもっと良いやり方があるのかもしれない)


2017/7/12 追記
Ruby2.1以降であれば、コメントで教えてもらった方法が一番良さそうです。

1.step do |i|
  puts "無限ループ#{i}回目"
  # => 無限ループ1回目
  # => 無限ループ2回目
  # => 無限ループ3回目
end

module Kernel
  def loop_with_index(ini = 0)
    cnt = ini
    loop do
      yield(cnt)
      cnt += 1
    end
  end
end

以下のように使える。

loop_with_index do |i|
  puts "無限ループ#{i}回目"
  # => 無限ループ0回目
  # => 無限ループ1回目
  # => 無限ループ2回目
end

ループカウンタの初期値も設定できる。

loop_with_index(5) do |i|
  puts "無限ループ#{i}回目"
  # => 無限ループ5回目
  # => 無限ループ6回目
  # => 無限ループ7回目
end

おまけ

昔(Ruby 1.8以前)はこういうバッドノウハウ的な手段もあったようだ。

無限ループ内でループ回数を数えるメモ

5
2
8

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
5
2