开发者

Dynamic change of "each" loops in Ruby

开发者 https://www.devze.com 2022-12-16 01:28 出处:网络
I am a newie in Ruby and I am facing a problem regarding \"each\"-like loops. Suppose a code like the following

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 un开发者_如何转开发til 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

Tryskele


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)


No.

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

or

startIndex = 1
endIndex = 200

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

精彩评论

暂无评论...
验证码 换一张
取 消