Unverified Commit 126d5548 authored by ksss's avatar ksss

Reimplement Enumerable#cycle

Fix pattern of infinite loop
And support all specs in https://github.com/ruby/spec/blob/27960d06e0ce92c37f074450f0eab4b0519b118c/core/enumerable/cycle_spec.rb without Enumerable#size
parent 3d946a80
...@@ -573,35 +573,38 @@ module Enumerable ...@@ -573,35 +573,38 @@ module Enumerable
# a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c. # a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
# #
def cycle(n=nil, &block) def cycle(nv = nil, &block)
return to_enum(:cycle, n) if !block && n.nil? return to_enum(:cycle, nv) unless block
ary = [] n = nil
if n.nil?
self.each do|*val| if nv.nil?
ary.push val n = -1
block.call(*val) else
unless nv.respond_to?(:to_int)
raise TypeError, "no implicit conversion of #{nv.class} into Integer"
end end
loop do n = nv.to_int
ary.each do|e| unless n.kind_of?(Integer)
block.call(*e) raise TypeError, "no implicit conversion of #{nv.class} into Integer"
end
end end
else return nil if n <= 0
raise TypeError, "no implicit conversion of #{n.class} into Integer" unless n.respond_to?(:to_int) end
n = n.to_int ary = []
self.each do|*val| each do |*i|
ary.push val ary.push(i)
end yield(*i)
count = 0 end
while count < n return nil if ary.empty?
ary.each do|e|
block.call(*e) while n < 0 || 0 < (n -= 1)
end ary.each do |i|
count += 1 yield(*i)
end end
end end
nil
end end
## ##
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment