3

我想要一个方法:

def time_between(from, to)
  ***
end

time_between 10.am.of_today, 3.pm.of_today # => 1pm Time object
time_between 10.am.of_today, 3.pm.of_today # => 3pm Time object
time_between 10.am.of_today, 3.pm.of_today # => 10:30am Time object
# I mean random

这里有两个问题:如何实现***?以及如何实施x.pm.of_today

4

4 回答 4

8

红宝石 1.9.3

require 'rubygems'
require 'active_support/all'

def random_hour(from, to)
  (Date.today + rand(from..to).hour + rand(0..60).minutes).to_datetime
end

puts random_hour(10, 15)
于 2013-01-01T09:22:25.810 回答
0

这是第一次尝试:

def time_between(from, to)
  today = Date.today.beginning_of_day
  (today + from.hours)..(today + to.hours).to_a.sample
end

虽然它的工作方式如下:

time_between(10, 15) # => a random time between 10 am and 3 pm

我认为就足够了,但我会开放以获得更好的解决方案。

于 2013-01-01T04:10:52.347 回答
-1

要获得随机时隙,您需要计算两次之间的距离。获取具有该距离跨度的随机值。最后将其添加到您的时间。

类似的东西:(但我不打算测试它)

def time_between(from, to)
  if from > to
    time_between(to, from)
  else
    from + rand(to - from)
  end
end

至于创建 DSL 的时间。你可以看看 Rails 是如何做到的。但是要得到你想要的东西。只需创建一个代表一天中的小时数的类。使用 Fixnum 上的 am 或 pm 调用来实例化它。of_today然后为(以及您想要的任何其他方法)编写方法。

class Fixnum
  def am
    TimeWriter.new(self)
  end

  def pm
    TimeWriter.new(self + 12)
  end
end

class TimeWriter
  MINUTES_IN_HOUR = 60
  SECONDS_IN_MINUTE = 60
  SECONDS_IN_HOUR = MINUTES_IN_HOUR * SECONDS_IN_MINUTE

  def initialize hours
    @hours = hours
  end

  def of_today
    start_of_today + (hours * SECONDS_IN_HOUR)
  end

  private

  attr_reader :hours

  def start_of_today
    now = Time.now
    Time.new(now.year, now.month, now.day, 0, 0)
  end
end

您应该添加一些超过 24 小时的错误处理。

于 2013-01-01T04:43:03.240 回答
-1

此代码尊重分钟和小时作为输入。

require 'rubygems'
require 'active_support/all'

def random_time(from, to)
  from_arr = from.split(':')
  to_arr   = to.split(':')
  now      = Time.now
  rand(Time.new(now.year, now.month, now.day, from_arr[0], rom_arr[1])..Time.new(now.year, now.month, now.day, to_arr[0], to_arr[1]))
end

puts random_time('09:15', '18:45')

另一个简短的方法来做同样的事情:

require 'rubygems'
require 'active_support/all'

def random_time(from, to)
  now      = Time.now
  rand(Time.parse(now.strftime("%Y-%m-%dT#{from}:00%z"))..Time.parse(now.strftime("%Y-%m-%dT#{to}:00%z")))
end

puts random_time('09:15', '18:45')
于 2017-06-29T10:52:26.113 回答