Home > Software engineering >  Divide contents of one hash with contents of another in Rails
Divide contents of one hash with contents of another in Rails

Time:01-13

So i have 2 hashes created

total_spend = monthly_subscriptions_new.group_by_day(:created_at).sum(:total_spend)
total_subs = monthly_subscriptions_new.group_by_day(:created_at).count

the result is a hash with Date:value e.g. total_spend

Jan 1:300

Jan 2:400

Jan 3:500

and total_subs

Jan 1: 5

Jan 2: 6

Jan 3: 7

i want to divide the total spend value by the total count and represent it in a new hash

So i want a new hash with

Jan 1: 60

Jan 2 : 67

Jan 3: 71

etc.

CodePudding user response:

You can use ActiveRecord::Calculations#average like this:

daily_average = monthly_subscriptions_new.group_by_day(:created_at)
                                         .average(:total_spend)
  •  Tags:  
  • Related