ruby - Ruby - 我希望代码只在特定条件下工作,但不知道该怎么做
问题描述
我知道我一定遗漏了一些东西,arr2.each_index
但我想不出还有什么可以添加的......我的大脑正在融化大声笑下面的代码应该只在 arr2 中没有大于 num 的“num”时执行,但是现在只要 arr2 中有一个大于 num 的“num”,它们就会执行。我希望这个问题是有道理的。
arr = [{"num":1,"head":5},{"num":3,"head":1},{"num":4,"head":1},{"num":5,"head":7}]
arr2 = [{"init1":[{"num":2,"head":1}]},{"init2":[{"num":35,"head":2}]},{"init3":[{"num":98,"head":1}]},{"init4":[{"num":51,"head":1},{"num":77,"head":5}]}]
arr3 = []
puts "Card you want to place outside? "
num = gets.chomp.to_i
def add_card_to_init(arr, arr2, arr3, num)
arr.each_with_index do |card, index|
if card[:num] == num
catch :skip do
arr2.each_index do |index|
x = arr2[index].values[0]
if num > x[x.length-1][:num]
#code
puts "num > init"
else
# code only runs when no num > x[x.length-1][:num]
puts "num < init"
throw :skip
end
end
end
end
end
end
add_card_to_init(arr, arr2, arr3, num)
当 num = 3 时期望输出
num > init
但我得到的是
num > init
num < init
提前致谢!
解决方案
the easiest way would be to set a flag "smaller" to true
before you enter the each_index
loop and set it to false
inside the loop if init >= num
. And then run your code outside the loop based on the flag. That's not elegant but quick and dirty. Optionally you can leave the loop on the first false
event.
推荐阅读
- excel - 将单元格值拆分为多行而不从其他单元格复制数据
- python - 找到熊猫时间序列之间的相关性
- sql - 使用 D365 中另一个表中的字段过滤父数据源
- css - 为什么这个固定元素不水平居中?
- google-cloud-firestore - AngularFire - 如何设置日志记录级别?
- java - 遍历集合的arraylist
- javascript - 无法正确更新父对象状态
- c# - 使用 autofac 时会出现此错误:“不支持返回 System.IServiceProvider 的配置服务。”
- arrays - Range 类型数组和非类型数组赋值中的效率与功能
- websocket - 如何将 ConnectedSocket 注入 NestJS 中的服务