Dynamically changing "every" loop in Ruby

I am new to Ruby, and I ran into a problem regarding "every" type of loops. Assume the code is as follows

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 work up to 200, and not up to 150. Is there a way to change the loop limits in dynamic mode in Ruby?

Thank you in advance for your help.

Tryskele

+3
source share
5 answers

Why not easy break?

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

'because it is really bad practice to dynamically change loop constraints.

+8
source
startIndex= 1
endIndex= 200

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

endIndex= 150
range # => 1..200

(a..b) Range. Range , . , . , , Range . , Range, . .

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

, , , break

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

, , , . , , :

p *(1..150)
+2

.

, .

?

0

150, .

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
0

Source: https://habr.com/ru/post/1727849/


All Articles