首页 > 解决方案 > 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

提前致谢!

标签: rubyloops

解决方案


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.


推荐阅读