Frage

I'm trying to find the frequency of values in an array using a frequency hash. However, my frequency hash isn't grouping the array items properly - they're all being counted just once. Here's my code:

require 'time'
require 'date'   

def peak_hours(reg_date)
    arr = []
    freq = Hash.new(0)
    format = "%m/%d/%y %H:%M"
    arr << DateTime.strptime(reg_date, format).hour
    arr.each { |v| freq[v] += 1 }
    puts freq
end

contents.each do |row|
    reg_date = peak_hours(row[:regdate])
end

Here's the output:

{10=>1}
{13=>1}
{13=>1}
{19=>1}
{11=>1}
{15=>1}
{16=>1}
{17=>1}
{1=>1}
{16=>1}
{18=>1}
{21=>1}
{11=>1}
{13=>1}
{20=>1}
{19=>1}
{21=>1}
{16=>1}
{20=>1}

Can anyone tell me why the keys are each being counted once, rather than returning a frequency?

War es hilfreich?

Lösung

The arr and freq objects are local to the peak_hours method, so they are destroyed whenever the method ends. It looks like you are calling the peak_hours method for every reg_date, and each time you call it it's making a new array and a new frequency hash, putting just the one value in each of them.

I think what you want to do is make your frequency hash right before wherever you are looping through your reg_dates, then update the frequency hash for each reg_date right inside the loop.

Andere Tipps

Here's the solution I found, with the help of Jeremy Ruten's comment.

def peak_hours(reg_date)
    arr = []
    format = "%m/%d/%y %H:%M"
    arr << DateTime.strptime(reg_date, format).hour
end

freq = Hash.new(0)
contents.each do |row|
    arr = []
    reg_date = peak_hours(row[:regdate])
    reg_date.each do |i|
        arr << i
        arr.each { |v| freq[v] += 1 }
    end
end
puts freq

It seems kind of clunky so any suggestions are welcome.

Remember to indent properly. Try this out for readability:

def parse_date(date)
  format = "%m/%d/%y %H:%M"
  DateTime.strptime(date, format).hour
end

hours = contents.map { |row| parse_date(row[:regdate]) }

peak_hours = Hash.new(0)
hours.each { |hour| peak_hours[hour] += 1 }
p peak_hours
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top