0

this is pretty straight forward im sure, but im feeling braindead right now, and can't figure this out....

I have this JSON response, and just want to grab all the values for the key "price", and dump them all into an array, so i can get the average for both of them.

{
  "status": "success",
  "data": {
    "network": "DOGE",
    "prices": [
      {
        "price": "0.00028055",
        "price_base": "USD",
        "exchange": "bter",
        "time": 1407184167
      },
      {
        "price": "0.00022007",
        "price_base": "USD",
        "exchange": "cryptsy",
        "time": 1407184159
      }
    ]
  }
}

this is my code thus far:

data = ActiveSupport::JSON.decode(response)
        status = data["status"]
        if status == "success"
          total = ......what do i need to do here?...
       end

thanks in advance :)

gypsyDev
  • 1,232
  • 1
  • 14
  • 22

1 Answers1

1

How to sum array of numbers in Ruby?

Except you yield a hash, not a number. So you drill in.

And since the values are strings, you have to convert them to floats to do math.

total = data["data"]["prices"].reduce(0.0) do |sum, hash|
  sum + hash["price"].to_f
end

Out of curiosity, how were you stuck? What was the logical gap in your understanding that prevented you from finding a solution?

Community
  • 1
  • 1
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337