Search code examples
ruby-on-railsrails-geocoder

Can't Access Contents of Geocoder Array in Rails


I'm using the search function in geocoder, specifically the one for an IP address:

Geocoder.search("204.57.220.1")

When I type the command into the console and store the results as a variable I can view the contents:

[#<Geocoder::Result::Freegeoip:0x0000000241d848 @data={"ip"=>"204.57.220.1", 
"country_code"=>"US", "country_name"=>"United States", "region_code"=>"WA",
"region_name"=>"Washington", "city"=>"Redmond", "zip_code"=>"98052", 
"time_zone"=>"America/Los_Angeles", "latitude"=>47.674, "longitude"=>-122.122, 
"metro_code"=>819}, @cache_hit=nil>] 

but I can't figure out how to access the results. I've tried:

results.@data.zip_code, results[@data.zip_code], results[@data.results] and pretty much every other combonation I could think of. Any ideas?


Solution

  • Note that this returns an array. This means that you need to do something like:

    results = Geocoder.search("204.57.220.1")
    first_result = results.first
    p first_result.data
    p first_result.data['ip']