Dinukaperera
Dinukaperera

Reputation: 97

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.

Upvotes: 0

Views: 5905

Answers (3)

Zoran
Zoran

Reputation: 4226

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.

Upvotes: 1

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

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

Upvotes: 0

Ursus
Ursus

Reputation: 30056

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 

Upvotes: 4

Related Questions