【问题标题】:Iterate over an array n items at a time and continue the iteration一次迭代数组 n 项并继续迭代
【发布时间】:2017-10-04 03:57:37
【问题描述】:

我正在尝试构建一个 CLI。我想打印存储在我的数组中的每个对象的名称。这就是我的数组的样子:

my_arr = [#<MyObject::Obj:0x007f828daf33b0>, #<MyObject::Obj:0x007f358daf33b0>..]

我希望用户采取措施一次显示 200/1000 个名称,而不是一次显示一个长列表。这是我的代码:

my_arr.each_with_index do |my_obj, index|
  puts "#{index} #{my_obj.name}"
end

我正在考虑使用case 语句来构建用户交互部分,但是在寻找拆分我的数组的方法时遇到了问题。如何开始对我的数组进行迭代,从迭代中脱颖而出(询问用户输入),然后继续从我离开的地方迭代?

【问题讨论】:

  • 已更新,希望现在应该更清楚了。
  • 任何答案有帮助吗?
  • 今晚晚些时候我会去看看,谢谢到目前为止所有的建议!

标签: arrays ruby loops


【解决方案1】:

Ruby 有一个 Enumerable#each_slice 方法,它会为您提供分组数组,这可以让您执行类似的操作:

my_arr = my_arr.collect.with_index do |my_obj, index|
  "#{index} #{my_obj.name}" # do this all the way up here to get the original index
end.each_slice(5)

length = my_arr.size - 1 # how many groups do we need to display
my_arr.each.with_index do |group, index|
  puts group.join("\n") # show the group, which is already in the desired format

  if index < length # if there are more groups to show,
                    # show a message and wait for input
    puts "-- MORE --"
    gets
  end
end

【讨论】:

  • 不需要初始中介Array。像这样的东西同样可以很好地工作my_arr.each_with_index.each_slice(5) {|slice| puts slice.map {|e,i| "#{i} #{e}"}; gets} 其中5 是每次输入时要显示的元素数
  • 我最终使用了这个解决方案,它奏效了。我最终切片了我迭代打印的数组。我将它与nextbreak 结合使用来停止或继续我的循环。感谢所有答案,如果我周末有时间,我会尝试其他解决方案。
【解决方案2】:

您可以使用breaknext。一个简短的演示 -

def foo_next(arr)
  arr.each_with_index { |item, index| 
    next if index % 2 == 0
    puts item
  }
end


def foo_break(arr)
  arr.each_with_index { |item, index| 
    puts item
    break if index % 2 == 0
  }
end

nums = (1..10).to_a

foo_next(nums) # prints 2 4 6 8 10

foo_break(nums) # prints 1

【讨论】:

    【解决方案3】:

    使用enumerator 启用停止/继续进程:

    arr = ('a'..'j').to_a
     #=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
    enum = arr.to_enum
    
    def taker n, enum
      n.times.with_object [] { |_, o| o << enum.next }
    end
    

    然后取多少你想要的元素...

    taker 2, enum
     #=> ["a", "b"]
    

    ...从你离开的地方继续:

    taker 3, enum
     #=> ["c", "d", "e"]
    taker 1, enum
     #=> ["f"]
    

    如何打印输出和/或用户提示取决于您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2011-04-26
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多