scheduler with for loop ruby

Asked by At

hello I am coding for my hobby. I am trying to code a twitchbot. I want to do scheduler with for loop

I tried that code but it‘s just printing me !prima btw scheduler's timer so sume2 is working fine.

require "rufus-scheduler"

scheduler =
sume = ['!prime', 'sea', 'ase', '!prima']
sume2 = ['30s', '20s', '10s', '40s']
s3 = sume2.length - 1

for x in 0..s3
  scheduler.interval sume2[x] do 
    puts sume[x]

what can I do about that.

1 Answers

user3708201 On

Your problem here is you are using a for loop instead of an Enumerable method such as each.

Short answer, just change for x in 0..s3 to sume2.each_index do |x|

Longer answer, you can compare the following:

for x in 0..3 { loop { puts(x); sleep 1 } }


(0..3).each do |x| { loop { puts(x); sleep 1 } }

The first just prints 3 repeatedly, but the second prints 1,2,3 as intended

Why? It's because with the for loop. your x variable gets overwritten each loop. With each, your x variable is scoped to the block and you have a closure.

For more explanation, see Closures and for loops in Ruby, or, or just google "closures in ruby"

Note, it's not idiomatic to use for loops in Ruby, for this particular reason