我正在尝试获取:visits
值。我正在使用此代码来访问值
puts "#{my_hash[0]['metrics'][0][:visits]}"
并收到此错误:
undefined method `[]'
已编辑:以下是puts my_hash
{"xml"=>"<entry><id>ID_DATA</id><updated>2013-04-01T18:10:36.599Z</updated><title type=\"text\">ga:month=01 | ga:year=2013</title><link rel=\"alternate\" type=\"text/html\" href=\"http://www.google.com/analytics\" /><dxp:dimension name=\"ga:month\" value=\"01\" /><dxp:dimension name=\"ga:year\" value=\"2013\" /><dxp:metric name=\"ga:visits\" type=\"integer\" value=\"26248\" /><dxp:metric name=\"ga:bounces\" type=\"integer\" value=\"17174\" /></entry>", "id"=>"https://www.googleapis.com/analytics/v2.4/data?ids=ga:45872215&ga:month=01&ga:year=2013&start-date=2013-01-01&end-date=2013-03-28", "updated"=>Mon, 01 Apr 2013 18:10:36 +0000, "title"=>"ga:month=01 | ga:year=2013", "dimensions"=>[{:month=>"01"}, {:year=>"2013"}], "metrics"=>[{:visits=>26248.0}, {:bounces=>17174.0}]}
{"xml"=>"<entry><id>ID_DATA</id><updated>2013-04-01T18:10:36.599Z</updated><title type=\"text\">ga:month=02 | ga:year=2013</title><link rel=\"alternate\" type=\"text/html\" href=\"http://www.google.com/analytics\" /><dxp:dimension name=\"ga:month\" value=\"02\" /><dxp:dimension name=\"ga:year\" value=\"2013\" /><dxp:metric name=\"ga:visits\" type=\"integer\" value=\"24808\" /><dxp:metric name=\"ga:bounces\" type=\"integer\" value=\"16716\" /></entry>", "id"=>"https://www.googleapis.com/analytics/v2.4/data?ids=ga:45872215&ga:month=02&ga:year=2013&start-date=2013-01-01&end-date=2013-03-28", "updated"=>Mon, 01 Apr 2013 18:10:36 +0000, "title"=>"ga:month=02 | ga:year=2013", "dimensions"=>[{:month=>"02"}, {:year=>"2013"}], "metrics"=>[{:visits=>24808.0}, {:bounces=>16716.0}]}
{"xml"=>"<entry><id>ID_DATA</id><updated>2013-04-01T18:10:36.599Z</updated><title type=\"text\">ga:month=03 | ga:year=2013</title><link rel=\"alternate\" type=\"text/html\" href=\"http://www.google.com/analytics\" /><dxp:dimension name=\"ga:month\" value=\"03\" /><dxp:dimension name=\"ga:year\" value=\"2013\" /><dxp:metric name=\"ga:visits\" type=\"integer\" value=\"23556\" /><dxp:metric name=\"ga:bounces\" type=\"integer\" value=\"16261\" /></entry>", "id"=>"https://www.googleapis.com/analytics/v2.4/data?ids=ga:45872215&ga:month=03&ga:year=2013&start-date=2013-01-01&end-date=2013-03-28", "updated"=>Mon, 01 Apr 2013 18:10:36 +0000, "title"=>"ga:month=03 | ga:year=2013", "dimensions"=>[{:month=>"03"}, {:year=>"2013"}], "metrics"=>[{:visits=>23556.0}, {:bounces=>16261.0}]}
我正在使用Gattica to_hash
方法。 https://github.com/chrisle/gattica
my_hash = data.to_h['points']
答案 0 :(得分:0)
文档给出了这个荒谬的咒语:
puts my_hash.first.metrics.detect { |metric| metric.key == :visits }.value