Plucking out all hash keys that has a specific word

683 views Asked by At

How do you pluck out a hash key that has for example

Hash 1 {sample => {apple => 1, guest_email => [email protected] }}

Hash 2 {guest => {email => [email protected]}}

Lets say I want 1 method that will pluck out the email from either of those hashes, is there any way I can that like lets say hash.get_key_match("email")

3

There are 3 answers

0
m.seliverstov On

I guess that you need the deep search. There is no method from the box.

You need use recursion for this goal.

I suspect that your issue can be solved by:

class Hash
  def deep_find(key, node = self)
    searchable_key = key.to_s
    matched_keys = node.keys.select { |e| e.to_s.match?(searchable_key) }
    return node[matched_keys.first] if matched_keys.any?

    node.values
        .select { |e| e.respond_to?(:deep_find) }
        .map { |e| e.deep_find(key, e) }
        .flatten.first
  end
end

h = {a_foo: {d: 4}, b: {foo: 1}}
p (h.deep_find(:foo))
# => {:d=>4}

h = {a: 2, c: {a_foo: :bar}, b: {foo: 1}}
p (h.deep_find(:foo))
# => :bar
0
imposterisasking On

you can use this

hash = { first_email: 'first_email', second_email: 'second_email' }


hash.select { |key, _value| key =~ /email/ }.map {|k, v| v}
4
Frederik Spang On

You may use Hash#select to only return keypairs, matching the block:

h = { guest_email: 'some_mail', other_key: '123', apple: 1 }

h.select { |key, _value| key =~ /email/ }
#=> { guest_email: 'some_mail' }