Radek
Radek

Reputation: 11111

how does Enumerable#cycle work? (ruby)

looper = (0..3).cycle
20.times { puts looper.next }

can I somehow find the next of 3? I mean if I can get .next of any particular element at any given time. Not just display loop that starts with the first element.

UPDATE

Of course I went though ruby doc before posting my question. But I did not find answer there ...

UPDATE2

input

looper = (0..max_cycle).cycle

max_cycle = variable that can be different every time the script runs

looper = variable that is always from interval (0..max_cycle) but the current value when the script starts could be any. It is based on Time.now.hour

output

I want to know .next value of looper at any time during the running time of the script

Upvotes: 0

Views: 1148

Answers (2)

Teoulas
Teoulas

Reputation: 2963

Your question is not very clear. Maybe you want something like this?

(current_value + 1) % (max_cycle + 1)

If, for example, max_cycle = 3 you will have the following output:

current_value    returns
      0             1
      1             2
      2             3
      3             0

Upvotes: 4

Related Questions