Skip to content

Instantly share code, notes, and snippets.

@JamesDullaghan
Created June 24, 2013 23:02
Show Gist options
  • Save JamesDullaghan/5854523 to your computer and use it in GitHub Desktop.
Save JamesDullaghan/5854523 to your computer and use it in GitHub Desktop.
sleep counter irc help

How would I go about mapping an array of hashes that are nested inside of an array??? I need to get an array returned for each :hours for each month, so I can then use the median method and get an average for each month. I can do it in the views, but using

<% @sleep_months.each do |month, sleep| %>
  <ul><%= month.strftime("%B") %>
  <% for sleeps in sleep %>
    <li><%= sleeps.hours %></li>
  <% end %>
  </ul>
<% end %>

I don't want to use this way as it's not very concise for controller code. Please let me know if there is a ruby method other than map, or show me the correct way to use map to

def index

  # Sleep.all for current_user
  @sleeps = current_user.sleeps
  # Sleep grouped and sorted in order by month
  @sleep_months = @sleeps.group_by { |s| s.beginning_of_month }.sort { |a,b| a[0] <=> b[0] }

  # returns ["Jan", "Feb", "Mar", "Jun", "Oct", "Nov"], GREAT!
  @array_for_average_sleep_months = @sleep_months.map { |month, sleep| month.strftime("%b") }

  @array_for_hours_slept_per_month = ?????
  # ????? for array of hours of sleep per month to
  @monthly_average_sleep_time = median(@array_for_hours_slept_per_month)

  raise
  respond_to do |format|
    format.html { render action: 'index' }
    format.js
  end
end

def median(array)
  if array.empty?
    current_user.sleeps.new
  else
    sorted = array.sort
    len = sorted.length
    return (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0
  end
end

data looks like this from @sleep_months:

[[Tue, 01 Jan 2013, [#<Sleep id: 10, user_id: 1, hours: 6, created_at: "2013-06-24 02:35:15", updated_at: "2013-06-24 02:35:15", sleep_date: "2013-01-01">]], [Fri, 01 Feb 2013, [#<Sleep id: 11, user_id: 1, hours: 9, created_at: "2013-06-24 02:36:38", updated_at: "2013-06-24 02:36:38", sleep_date: "2013-02-06">, #<Sleep id: 15, user_id: 1, hours: 7, created_at: "2013-06-24 02:38:31", updated_at: "2013-06-24 02:38:31", sleep_date: "2013-02-20">]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment