Tutorial :Dynamic change of “each” loops in Ruby


I am a newie in Ruby and I am facing a problem regarding "each"-like loops. Suppose a code like the following

startIndex = 1  endIndex = 200    (startIndex..endIndex).each do |value|     p value     if value>150 then endIndex=100  end  

When I run the code it will run until 200, not until 150. Is there any way to change the limits of the loop range dynamically in Ruby?

Thanks in advance for your help



Why not just break?

(startIndex..endIndex).each do |value|      p value      break if value>=150  end  

'cause it's really bad practice to dynamically change loop limits.


startIndex= 1  endIndex= 200    range= (startIndex .. endIndex) # => 1..200    endIndex= 150  range # => 1..200  

(a..b) creates an Object of the Range class. A Range Object does not hold pointers to the variables you pass. It rather hold's references to the objects, the variables points to. If you change the variable, so the variable hold a reference to another object, the Range still holds the reference to the old object. So you can change the Range by changing the object itself. But there is no way to change an Integer once it's created.

a= "abc"  b= "def"  range= (a..b) # => "abc".."def"  b.sub!("e", "$")  range # => "abc".."d$f"  

If the only thing you want to do is escape from the loop, you could just use break

(a..b).each do |v|    break if something  end  


No, what you are trying to do won't work. However, it is also completely unnecessary, since there is a much better, idiomatic way to do the exact same thing you are trying to do:

p *(1..150)  



This is almost certainly not what you want to do.

What problem are you trying to solve?


If you just want to stop printing it at 150, these might work.

startIndex = 1  endIndex = 200    (startIndex..endIndex).each do |value|     p value if value <= 150  end  


startIndex = 1  endIndex = 200    (startIndex..endIndex).each do |value|     p value     if value >= 150        break     end  end  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »