【问题标题】:Plucking out all hash keys that has a specific word提取所有具有特定单词的哈希键
【发布时间】:2020-10-22 09:51:01
【问题描述】:

您如何提取具有例如的哈希键

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

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

假设我想要一种方法来从这些哈希中提取电子邮件,有什么方法可以让我说 hash.get_key_match("email")

【问题讨论】:

  • 你的哈希键也总是变化???
  • 是的,基本上如果我从外部源给出了 2 种类型的哈希,那么可以说我必须处理这 2 种类型
  • 一大堆:h = {:sample => {:apple => 1, :guest_email => 'my_email@example.com' }}; h.to_s[/(?<=email=>")[^"]+/] #=> "my_email@example.com".

标签: ruby-on-rails ruby ruby-hash


【解决方案1】:

您可以使用Hash#select 仅返回与块匹配的密钥对:

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

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

【讨论】:

  • 这对我来说是一个好的开始,当有匹配时我如何只提取值(没有键)?
  • 你可以去hash.values
  • hash.values.select {|key, value| key =~ /email/} 返回 []
  • h.select { |key, _value| key =~ /email/ }.values
【解决方案2】:

我猜你需要深度搜索。 盒子里没有方法。

您需要为此目标使用递归。

我怀疑您的问题可以通过以下方式解决:

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

【讨论】:

    【解决方案3】:

    你可以用这个

    hash = { first_email: 'first_email', second_email: 'second_email' }
    
    
    hash.select { |key, _value| key =~ /email/ }.map {|k, v| v}
    

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 2013-12-13
      • 2016-05-29
      相关资源
      最近更新 更多