1

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

6
  • 1
    Try total_hours = @payload[:activities].sum{|activity| activity[:hours].to_f} Commented Aug 14, 2019 at 5:00
  • @jvillian Thank you so much it worked!! Can you say what was i doing wrong Commented Aug 14, 2019 at 5:04
  • Yes, adding as an answer right now. Commented Aug 14, 2019 at 5:06
  • You have targeted object instead of array. thats the reason [:activities] is array of obj. Commented Aug 14, 2019 at 5:09
  • Oh my bad, Thank you. Can you add this as an answer so i can choose it as my answer so it would be helpful to others too. Commented Aug 14, 2019 at 5:12

2 Answers 2

2

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

@payload[:activities].pluck(:hours).reduce(:+)
Sign up to request clarification or add additional context in comments.

2 Comments

@payload[:activities].sum(:hours) will work and is shorter.
No, you'll have an undefined method + for :hours Symbol. Check it.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.