7

I have the following hash:

{"title"=>"ga:browser=Firefox", "dimensions"=>[{:browser=>"Firefox"}], "metrics"=>[{:pageviews=>25474}], "id"=>"http://www.google.com/analytics/feeds/data?ids=ga:3906565&amp;ga:browser=Firefox&amp;start-date=2010-02-06&amp;end-date=2011-02-06", "updated"=>#<DateTime: 212163710400001/86400000,-1/3,2299161>}

How would I print the value of pageviews?

1 Answer 1

14

Well, you have a hashmap (not an array) which maps the key "metrics" to an array. That array contains a hash as its only element. And that hash maps the key :pageviews to the value 25474. So to get that value you can do:

the_hash["metrics"][0][:pageviews]

This assumes that the hash with the :pageviews key will always be at position 0 in the array, which the key "metrics" is mapped to.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, is there an easy way to tell if it is a hashmap or array? or can you just tell by the structure?
@Tom: A hashmap is surrounded by curly braces and an array by square brackets. Also if a hash is not empty it contains key-value pairs in the form key => value, while an array only contains single values (of course those might themselves be arrays or hashes).
You can ask Ruby what it is by using variablename.class, where "variablename" is some variable you want to know about. For instance, variable = {}; puts variable.class will output "Hash" or variable = []; puts variable.class will output "Array".

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.