0

I wrote a loop script from an array like this:

a = [1, 2, 3, 4]
a.cycle.each{|i| p i; sleep 1}

And I want to start a loop from a specified index.

index = 2
(a[index..-1] + a.cycle).each{|i| p i; sleep 1}

This code ends up with error TypeError: no implicit conversion of Enumerator into Array.

How can I write a loop code like this case?

1
  • 1
    It says in the docs that if no block is given to cycle it returns an enumerator instead hence the type error. Commented Sep 22, 2014 at 2:11

3 Answers 3

2

You could use rotate:

a.rotate(new_index).cycle { ... }

(NOTE: I don't think you need the .each)

Sign up to request clarification or add additional context in comments.

Comments

2

rotate is the correct answer, but the reason your code wasn't working was because you were trying to concatenate the last part of the array and a.cycle, which is an Enumerator and probably not what you wanted. Furthermore, your code would output [3, 4, 1, 2, 3, 4] (if you fixed the other part) because you don't slice off the end when you concatenate the rest of the array.

Try this instead (actually, use rotate like @lurker said, but here's how to fix your original code):

(a[index..-1] + a[0...index]).cycle {|i| p i; sleep 1}

Comments

0

You could do it without Array#rotate. Suppose that for:

a = [1, 2, 3, 4]

the starting index were 2:

enum = a.cycle
2.times { enum.next }
enum.each { |i| p i; sleep 1 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.