2

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

Hash 1 {sample => {apple => 1, guest_email => my_email@example.com }}

Hash 2 {guest => {email => my_email@example.com}}

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")

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Berimbolo
  • 293
  • 2
  • 12

3 Answers3

3

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' }
Frederik Spang
  • 3,379
  • 1
  • 25
  • 43
1

you can use this

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


hash.select { |key, _value| key =~ /email/ }.map {|k, v| v}
wiwit
  • 73
  • 1
  • 7
  • 26
0

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
m.seliverstov
  • 195
  • 1
  • 6