jamby
jamby

Reputation: 606

How to access a hash that has a key that's an array and a value that's an integer

So I have a hash that looks like:

hash = { ["1", "2", "3"]=>"a", ["4", "5", "6"]=>"b", ["7", "8", "9"]=>"c" }

Though when I try to do something like hash[0] just a new line in my console shows up and if I try hash[0][0] it pops me an error that says [] method is undefined.

Now I'm wondering how to I access this in a way that I can do something like hash["1"] and it'll return me the "a".

I assume that since it lets me make hashes in this way I can access the content inside.

Upvotes: 0

Views: 76

Answers (2)

Nate Pinchot
Nate Pinchot

Reputation: 3318

I'm not sure why you would want to create a hash with a key that's an array, but it works :)

hash = { ["1", "2", "3"]=>"a", ["4", "5", "6"]=>"b", ["7", "8", "9"]=>"c" }

hash[["1", "2", "3"]]
=> "a"

You might want to consider the opposite:

hash = { "a"=>["1", "2", "3"], "b"=>["4", "5", "6"], "c"=>["7", "8", "9"] }

hash["a"]
=> ["1", "2", "3"]

Upvotes: 3

Dylan Markow
Dylan Markow

Reputation: 124409

There's not a direct built-in way to access something like this, but by using select you can filter out the key/value pair that has the "1" and get the value for it:

hash.select { |key| key.include?("1") }.values.first

This assumes that each integer only exists in a single key.

Upvotes: 2

Related Questions