【问题标题】:skip some iteration in ruby for loop在 ruby​​ for 循环中跳过一些迭代
【发布时间】:2015-08-16 09:23:12
【问题描述】:

如何在 ruby​​ 的 for 循环中实现这样的功能:

for(int i = 1;i<=10;i++){
        if (i == 7){
            i=9;
        }
        #some code here
    }

我的意思是说可以使用“下一步”跳过,但是如果我想通过更改变量值本身来跳转到不确定的迭代该怎么办。据我所知,循环适用于可枚举类型。我想通过索引将其作为变量循环,就像我们在 C++ 中所做的那样

【问题讨论】:

标签: ruby loops iteration skip


【解决方案1】:

对您的问题最准确的答案是使用while 循环,如下所示:

i = 0
while i < 10
  if i == 0 # some condition
    i = 9 # skip indexes
  else
    i += 1 # or not
  end
end

【讨论】:

    【解决方案2】:

    您可以做的事情很少:

    如果您想根据定义的逻辑跳过一些迭代,您可以使用:

    next if condition
    

    如果您的意图是在整个范围内随机迭代,您可以试试这个:

    (1..10).to_a.shuffle.each { |i| 
       # your code
    }
    

    如果你想随机迭代给定范围的某个块,试试这个:

    (1..10).to_a.shuffle.first(n).each { |i| # n is any number within 1 to 10
      # your code
    }
    

    【讨论】:

      【解决方案3】:

      为什么不采用递归方法? 喜欢

      foo(x)
      {
          if x == 7
          {
              return foo(9)
          }
          return foo(x+1)
      }
      

      【讨论】:

        【解决方案4】:
        (1..10).each do |i|
          next if(i == 7 || i == 8)
          # some code here
        end
        

        【讨论】:

          【解决方案5】:

          这个怎么样?

          array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
          
          array.each_with_index do |elem, idx|
              break if idx == 9
              # do something
              puts "element #{idx} with #{elem}"
          end
          

          【讨论】:

            猜你喜欢
            • 2021-11-15
            • 1970-01-01
            • 1970-01-01
            • 2021-08-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多