简体   繁体   中英

Change value of Enumerator in Ruby

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM