0

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Dinukaperera
  • 97
  • 1
  • 10

3 Answers3

4

You can do that if you make your hash an array, otherwise for the first access you have to use a key (well, ok, even 0 can be a key but is not present in your hash)

cities.to_a[0][1][1]
 => -87.61184692382812 

cities["l10"][1]
 => -87.61184692382812 
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Zoran
  • 4,196
  • 2
  • 22
  • 33
0

Use Hash#dig on Hashes

A Hash isn't indexable, because it's not guaranteed to be ordered (although pragmatically, recent MRI implementations maintain insert order). Instead, you need to look up by key and then index into the Array stored there as a value. In recent versions with support for Hash#dig, you can use the following syntax:

cities.dig 'l10', 1
#=> -87.61184692382812

Alternatively, you can convert the Hash object into an Array of arrays, and then index as you are trying to do in the original post. For example:

cities.to_a[0][1][1]
#=> -87.61184692382812
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199