Designated as .choose outside the loop is fixed inside the loop

This prints the same value every time:

x = [1, 2, 3].choose

live_loop :myloop do
  puts x
  sleep 1
end

Per this thread, I tried using set and get, but either I don’t understand yet or choose presents a different situation from ring. What’s the simplest way to get the variable to be freshly chosen from each loop?

Hey @blipson, nice question, thanks!

Maybe it might help to think of .choose as an action that chooses one of the items in the list. We then assign that choice to the variable x. After that choice and assignment takes place, you then start a live_loop which spins round reading the value assigned to x which never changes as it is only assigned to once right at the start of the program.

If we want different choices each time round the live loop, we need to call .choose every time round too - not just at the start of the program.

So a simple fix really:

live_loop :myloop do
  x = [1, 2, 3].choose
  puts x
  sleep 1
end

I hope that this helps!

1 Like