简体   繁体   English

Ruby:平均次数

[英]Ruby: Average array of times

I have the following method in my Array class: 我的Array类中有以下方法:

class Array
  def avg
    if partial_include?(":")
      avg_times
    else
      blank? and 0.0 or (sum.to_f/size).round(2)
    end
  end

  def avg_times
    avg_minutes = self.map do |x|
      hour, minute = x.split(':')
      total_minutes = hour.to_i * 60 + minute.to_i
    end.inject(:+)/size
    "#{avg_minutes/60}:#{avg_minutes%60}"
  end

  def partial_include?(search_term)
    self.each do |e|
      return true if e[search_term]
    end
    return false
  end
end

This works great with arrays of regular numbers, but there could instances where I have an array of times. 这非常适合常规数字数组,但是在某些情况下,我可能会有很多时间。

For example: [18:35, 19:07, 23:09] 例如: [18:35, 19:07, 23:09][18:35, 19:07, 23:09]

Anyway to figure out the average of an array of time objects? 反正找出时间对象数组的平均值?

So you need do define a function that can calculate the average of times formatted as strings. 因此,您需要定义一个函数,该函数可以计算格式化为字符串的平均时间。 Convert the data to minutes, avg the total minutes and then back to a time. 将数据转换为分钟,平均总分钟数,然后返回一个时间。

I would do it something like this: 我会做这样的事情:

a =  ['18:35', '19:07', '23:09']

def avg_of_times(array_of_time)
  size = array_of_time.size
  avg_minutes = array_of_time.map do |x|
    hour, minute = x.split(':')
    total_minutes = hour.to_i * 60 + minute.to_i
  end.inject(:+)/size
  "#{avg_minutes/60}:#{avg_minutes%60}"
end

p avg_of_times(a) # = > "20:17"

Then when you call you function you check if any/all items in your array is formatted as a time. 然后在调用函数时,检查数组中是否有任何/所有项目被格式化为时间。 Maybe using regexp. 也许使用正则表达式。

Average the Hours and Minutes Separately 平均小时和分钟

Here's a simple method that we're using: 这是我们正在使用的一种简单方法:

def calculate_average_of_times( times )
  hours   = times.collect{ |time| time.split( ":" ).first.to_i }  # Large Arrays should only
  minutes = times.collect{ |time| time.split( ":" ).second.to_i } # call .split 1 time.

  average_hours   = hours.sum / hours.size
  average_minutes = ( minutes.sum / minutes.size ).to_s.rjust( 2, '0' ) # Pad with leading zero if necessary.

  "#{ average_hours }:#{ average_minutes }"
end

And to show it working with your provided Array of 24-hour times, converted to Strings : 并显示它如何与您提供的24小时制Array一起使用,并转换为Strings

calculate_average_of_times( ["18:35", "19:07", "23:09"] )
#=> "20:17"

Thanks to @matt-privman for the help and inspiration on this. 感谢@ matt-privman在此方面的帮助和启发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM