0

I have a hash which holds a series of arrays with values in them:

av_hash = {9 => [2,4,6], 10 => [5,7], 11 => [2,3,7]} 

how can I check for the presence of a certain number in the array value of a certain hash key?

So if I wanted for example to find out if key 11 contains the number 2 in its array, what's the best way to go about this?

1
  • 2
    Get the array at the key and check it? I'm not sure what the issue actually is. Commented Feb 29, 2016 at 15:30

2 Answers 2

2

It's super straightforward. Get the item with given key using hash[key_name], then use Enumerable#include? to check if the array contains the element you want to find.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I couldn't work out if include? could be used with arrays within hashes. Will accept when I can
That should be Array#include?
2

You can either test the specific key you want or iterate over each key/val pair and return the key that includes the number you're looking for:

av_hash = {9 => [2,4,6], 10 => [5,7], 11 => [2,3,7]} search_for = 2 # see if specific key has `search_for` value in it: av_hash[11].includes? search_for # returns true if key 11's array includes 2 # get keys that contain the value: av_hash.map { |k, v| k if v.include? search_for }.compact # returns [9, 11] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.