Ruby 迭代数小时

标签 ruby loops time

假设我有一些关于开始时间和结束时间的用户输入:

  • 开始 = 09:00
  • 结束 = 01:00

如何显示这两个时间之间的所有时间?所以从09到23、0,再到1。

有简单的情况:

  • 开始 = 01:00
  • 结束 = 04:00

这只是一个问题 ((start_hour.to_i)..(end_hour.to_i)).select { |小时|

最佳答案

这可以通过自定义枚举器实现来解决:

def hours(from, to)
  Enumerator.new do |y|
    while (from != to)
      y << from
      from += 1
      from %= 24
    end
    y << from
  end
end

这给了你一些你可以像这样使用的东西:

hours(9, 1).each do |hour|
  puts hour
end

或者如果你想要一个数组:

hours(9,1).to_a
#=> [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0, 1]

关于Ruby 迭代数小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36844320/

相关文章:

Python tkinter : loop in Label

linux - 如何用Tcl/Tk语言创建一个带有文本模式控件的定时器

arrays - Perl循环遍历单个元素的数组哈希

javascript - 为什么这个阶乘查找算法的运行时复杂度不是 O(n!)?

c++ - std::chrono 有多准确?

Ruby:在类方法中使用模块方法

ruby - ChromeDriver Ruby 禁用图像

ruby - 导轨 : Generating Acts_as_Taggable_On tag counts from collection of tagged objects

ruby - 一次在字符串中插入多个字符

algorithm - 如何设计时间复杂度为 O(n log n) 的搜索算法?