Amal T S
Amal T S

Reputation: 57

How to calculate the sum of array inside hash ruby

Hai i am creating a json file with my data and i need to calculate the hours before i save it into the database

I am assigning that hash into a variable payload and tried doing this but it returns me an error TypeError (no implicit conversion of Symbol into Integer):

total_hours = @payload.sum{|activity| activity[:hours].to_f}

Hash before converting to json

{:activities=>
  [{:project=>1,
    :activity=>"my activity",
    :hours=>0.2e1,
    :date=>Sat, 10 Aug 2019 00:00:00 UTC +00:00},
   {:project=>2,
    :activity=>"Tester",
    :hours=>0.2e1,
    :date=>Thu, 01 Aug 2019 00:00:00 UTC +00:00},
   {:project=>2,
    :activity=>"Tester",
    :hours=>0.3e1,
    :date=>Thu, 01 Aug 2019 00:00:00 UTC +00:00}]}

I need to sum the hours of my array which is inside the hash. Thanks

Upvotes: 1

Views: 223

Answers (2)

Gustavo Toro
Gustavo Toro

Reputation: 450

If you are using Rails, here is a short way:

@payload[:activities].pluck(:hours).reduce(:+)

Upvotes: 2

jvillian
jvillian

Reputation: 20263

You should use:

total_hours = @payload[:activities].sum{|activity| activity[:hours].to_f}

You see, what you're wanting to do is, essentially:

[
  {
    :project=>1,
    :activity=>"my activity",
    :hours=>0.2e1,
    :date=>Sat, 10 Aug 2019 00:00:00 UTC +00:00
  },
  {
    :project=>2,
    :activity=>"Tester",
    :hours=>0.2e1,
    :date=>Thu, 01 Aug 2019 00:00:00 UTC +00:00
  },
  {
    :project=>2,
    :activity=>"Tester",
    :hours=>0.3e1,
    :date=>Thu, 01 Aug 2019 00:00:00 UTC +00:00
  }
].sum{|activity| activity[:hours].to_f}

But, you're calling .sum on the @payload variable, which is a hash. What you want is the value of the hash that is associated with the key :activities. Thus, you need to call .sum on @payload[:activities] where @payload[:activities] returns the array above.

Upvotes: 1

Related Questions