views:

93

answers:

2
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

+1  A: 

http://ruby-doc.org/core-1.9/classes/Enumerable.html#M003074

Azeem.Butt
Of course I went though ruby doc before posting my question. But I did not find answer there ...
Radek
+3  A: 

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
Teoulas
@Teoulas: :-) that's what I want. Can I use Enumerable#cycle for that?
Radek
@Radek, I don't think so. Enumerable objects are used to iterate over a collection of values/objects. In your case, you only need the first and the last number of a range. If you insist on calling a method, you could add one to ruby's Range.eg. (0..3).next_with_wrap(2) => 3
Teoulas
@Teoulas: I don't insist on anything. I'm looking for the best solution and learning on way... I wrote a method but I thought there must be something simpler then Enumerable#cycle came along. I thought I could use it. That's it. Your solution is much nices, easier than my method. I am happy with that. Thank you
Radek