kin*_*r88 1 ruby iteration loops for-loop escaping
我有一个带有if elsif语句的for循环.在第一个if,如果满足条件,我希望它停在那里并继续循环的下一次迭代.
这是我想要做的非常简化的版本:
array = [1,2,3,4,"x"]
for i in 0..(array.count -1)
if array[i] == "x"
#start next for loop iteration without executing the elsif
elsif array[i] < 3
puts "YAY!"
end
end
Run Code Online (Sandbox Code Playgroud)
我正在尝试做的是迭代一个数组,其中除了一个元素之外的所有元素都是整数,但其中一个是一个字符串.在字符串元素上,我需要循环(无论哪种类型最好)跳过其余代码并转到循环的下一次迭代.这很重要,因为第二个if语句使用'array_element <11条件',所以如果它在字符串元素上运行,我得到"String与11的比较失败"
所以我想要arr [x] [3]这就是我尝试的但它给了我8 8 8 8而不是一个8.
arr = [[1,2,3,"4"], [5,6,7,8], [9,10,11,12]]
arr.each{|x|
x.each {|i|
next if x[3].instance_of? String
if x[3] < 12 puts x[3]
end
}
}
Run Code Online (Sandbox Code Playgroud)
好的,这有效!! 谢谢你iAmRubuuu !!
arr = [1,2,3,"4"], [5,6,7,8], [9,10,11,12], [13,14,15,"16"], [17,18,19,20]]
arr.each_with_index{|x, i|
next if x.last.instance_of? String
if x.last < 21
puts x.last
end
}
Run Code Online (Sandbox Code Playgroud)
给我输出
8
12
20
Run Code Online (Sandbox Code Playgroud)
不要使用for in,使用each.
(0..10).each do |i|
next if i == 5
if i == 10
puts "YAY!"
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5558 次 |
| 最近记录: |