Ruby 1.8.7 Ruby 1.9
標準クラス・モジュール > Array > cycle
enum.cycle([n]) {|item| block }
cycle
メソッドは、要素の数だけブロックを繰り返し実行し、その繰り返しを引数n回続けます。繰り返しごとにブロック引数itemには各要素が順に入ります。戻り値はnil
です。ブロックを省略するとEnumerator
オブジェクトを返します。
(1..5).cycle(2) {|n| print "#{n} " } puts ""
1 2 3 4 5 1 2 3 4 5
引数nを省略すると、繰り返しを永遠に続けます。次の例は、Ctrl+Cキーを押すまで繰り返しを何度も続けます。
puts "Ctrl+C to stop" begin (1..5).cycle {|item| puts item; sleep(1) } rescue Interrupt puts "bye" end
Ctrl+C to stop 1 2 3 4 5 1 2 bye
cycle (Array)
: Array
クラスのcycle
メソッド。Ruby 1.8.7