I have this code in irb:
2.2.1 :001 > a = 0
=> 0
2.2.1 :002 > b = (a..a+6).step(3)
=> #<Enumerator: 0..6:step(3)>
2.2.1 :004 > puts b.inspect
#<Enumerator: 0..6:step(3)>
=> nil
2.2.1 :005 > a = 1
=> 1
2.2.1 :007 > puts b.inspect
#<Enumerator: 0..6:step(3)>
=> nil
What I want to achieve is to change the value of a
with every iteration, but a
stays with the same value, worse, Ruby just changes the value of a
to 0. Is there a way to declare dynamic Enumerators?, ones that change values every time I change the values of my variables?
Thank you.
When you write b = (a..a+6).step(3)
the expression is evaluated to roughly this: b = (0..6).step(3)
. Changing a
after this line, won't change b
. If you want to change b
you need to somehow reassign it , the simplest way is after you had changed a
to 1 repeat the assignment b = (a..a+6).step(3)