ruby Ruby:确定时间差异

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby:确定时间差异相关的知识,希望对你有一定的参考价值。

#!/opt/apps/ruby/ruby/bin/ruby
require 'date'

# Hold the time differences to calculate averages
time_diffs = []

# Get three time differences
1..3.times do
  initial_time = DateTime.now()
  sleep 1
  final_time   = DateTime.now()

  # Calculate the difference in seconds
  diff = ((first - second) * 24 * 60 * 60).to_i
  
  # Store the differences as an absolute value
  time_diffs << diff.abs
end

# ===================================================
# Calculate the average, min and max
# The inject, min, and max methods come from the 
# enumerable module which can be implemented on 
# and class that contains an each method.
# The ruby docs actually have a good description of 
# the inject, min, and max methods if you want to 
# how they work
# ===================================================
avg = time_diffs.inject(:+).to_f / time_diffs.size
min = avg.min
max = avg.max

# Display the Results
puts "The average time in seconds was '#{avg}'"
puts "The max time in seconds was '#{max}'"
puts "The min time in seconds was '#{min}'"

以上是关于ruby Ruby:确定时间差异的主要内容,如果未能解决你的问题,请参考以下文章