Skip to content

Commit 126d554

Browse files
committed
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
1 parent 3d946a8 commit 126d554

File tree

1 file changed

+26
-23
lines changed
  • mrbgems/mruby-enum-ext/mrblib

1 file changed

+26
-23
lines changed

mrbgems/mruby-enum-ext/mrblib/enum.rb

Lines changed: 26 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -573,35 +573,38 @@ def reverse_each(&block)
573573
# a.cycle(2) { |x| puts x } # print, a, b, c, a, b, c.
574574
#
575575

576-
def cycle(n=nil, &block)
577-
return to_enum(:cycle, n) if !block && n.nil?
576+
def cycle(nv = nil, &block)
577+
return to_enum(:cycle, nv) unless block
578578

579-
ary = []
580-
if n.nil?
581-
self.each do|*val|
582-
ary.push val
583-
block.call(*val)
579+
n = nil
580+
581+
if nv.nil?
582+
n = -1
583+
else
584+
unless nv.respond_to?(:to_int)
585+
raise TypeError, "no implicit conversion of #{nv.class} into Integer"
584586
end
585-
loop do
586-
ary.each do|e|
587-
block.call(*e)
588-
end
587+
n = nv.to_int
588+
unless n.kind_of?(Integer)
589+
raise TypeError, "no implicit conversion of #{nv.class} into Integer"
589590
end
590-
else
591-
raise TypeError, "no implicit conversion of #{n.class} into Integer" unless n.respond_to?(:to_int)
591+
return nil if n <= 0
592+
end
592593

593-
n = n.to_int
594-
self.each do|*val|
595-
ary.push val
596-
end
597-
count = 0
598-
while count < n
599-
ary.each do|e|
600-
block.call(*e)
601-
end
602-
count += 1
594+
ary = []
595+
each do |*i|
596+
ary.push(i)
597+
yield(*i)
598+
end
599+
return nil if ary.empty?
600+
601+
while n < 0 || 0 < (n -= 1)
602+
ary.each do |i|
603+
yield(*i)
603604
end
604605
end
606+
607+
nil
605608
end
606609

607610
##

0 commit comments

Comments
 (0)