Friday, 15 May 2015

ruby - Iterate an array of hashes -



ruby - Iterate an array of hashes -

i have hash key of cities , value array of hashes containing location data. looks this:

@locations = { "cities"=>[ {"longitude"=>-77.2497049, "latitude"=>38.6581722, "country"=>"united states", "city"=>"woodbridge, va"}, {"longitude"=>-122.697236, "latitude"=>58.8050174, "country"=>"canada", "city"=>"fort nelson, bc"}, ... ] }

i'd iterate through , print values key city:

woodbridge, va fort nelson, bc ...

for corrected info format:

@locations = { "cities"=>[ { "longitude"=>-77.2497049, "latitude"=>38.6581722, "country"=>"united states", "city"=>"woodbridge, va"}, { "longitude"=>-122.697236, "latitude"=>58.8050174, "country"=>"canada", "city"=>"fort nelson, bc" }] } @locations["cities"].each { |h| puts h["city"] } woodbridge, va fort nelson, bc

or save in array:

@locations["cities"].each_with_object([]) { |h,a| << h["city"] } #=> ["woodbridge, va", "fort nelson, bc"]

ruby arrays loops each hash

No comments:

Post a Comment