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.

4
  • What about puts cities[0][1]? Commented Apr 21, 2017 at 22:38
  • @rotgers that's not going to work because cities is not an array. "first" doesn't make a whole lot of sense for a hash. Commented Apr 21, 2017 at 22:39
  • Try cities["l10"][1] Commented Apr 21, 2017 at 22:39
  • Can u make it clear please. what you trying to achieve by this ?? Commented Apr 22, 2017 at 7:18

3 Answers 3

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 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.