Search code examples
arraysrubyruby-hash

How to access an array element inside a hash in Ruby


I have a hash of arrays of coordinates of locations like this:

cities = {
  "l10"=> [41.84828634806966,-87.61184692382812],
  "l11"=> [41.86772008597142,-87.63931274414062],
  "l12"=> [41.88510316124205,-87.60498046875],
  "l13"=>[41.84930932360913,-87.62420654296875]
}

To access the second value in the first array, I tried:

puts cities[0][1][1]

I want it to print out -87.61184692382812, but it doesn't. It gives me an error.


I am trying to iterate over the hash. Accessing it by using

puts cities["l10"][1]

doesn't work. But

puts cities[0][1][1]

worked when I converted it into an array.


Solution

  • Here's one way to access the second value of the first key of your hash:

    cities.values.first[1]
    # => -87.61184692382812
    

    This fetches the value of your first key (in this case it's that first array in the hash), and then retrieves by index the second element of that array.