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 = Rufus::Scheduler.new
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]
  end 
end

what can I do about that.

1 Answers

0
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
  Thread.new { loop { puts(x); sleep 1 } }
end

with:

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

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 https://scotch.io/tutorials/understanding-ruby-closures, or just google "closures in ruby"

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