Search code examples
rubyhashdetect

How do I iterate through a hash until I find a matching element?


I have a hash that maps integers to arrays. For example

{1 => ["abc"], 2 => ["ccc", "ddd"]}

How do I iterate through the hash until I find an entry in which the value only has an array size of 1? Normally I could do

arr.detect{|element| element.size == 1}

but that only works for arrays. I'm not sure how to apply a similar logic to hashes.


Solution

  • Same principle applies:

    h = {1 => ["abc"], 2 => ["ccc", "ddd"]}
    
    h.find do |_, l|
      l.size == 1
    end
    # => [ 1, ["abc"]]
    

    Now if you're looking for that as a more useful variable set:

    key, value = h.find do |_, l|
      l.size == 1
    end
    # => [ 1, ["abc"]]
    key
    # => 1
    value
    # => ["abc"]
    

    If you only care about the values, then it's even easier:

    list = h.values.find do |l|
      l.size == 1
    end