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:确定时间差异的主要内容,如果未能解决你的问题,请参考以下文章

如何解决 ruby​​ on rails 版本差异(向后/向前兼容性)

如何在ruby中获取旧值和新值之间的差异

ruby Ruby闭包的实验 - 突出了每个人最喜欢的小语言构造背后的差异,不一致和微妙之处

ruby 检查电子邮件内容差异。

ruby + =和= +之间的差异

十张图读懂 PHPPython Ruby 三大语言的差异