Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 取出所有具有特定单词的哈希键_Ruby On Rails_Ruby_Ruby Hash - Fatal编程技术网

Ruby on rails 取出所有具有特定单词的哈希键

Ruby on rails 取出所有具有特定单词的哈希键,ruby-on-rails,ruby,ruby-hash,Ruby On Rails,Ruby,Ruby Hash,例如,如何提取具有 散列1 {sample=>{apple=>1,guest\u email=>my_email@example.com}} 散列2 {guest=>{email=>我的_email@example.com}} 假设我想要一个方法,可以从这些散列中提取电子邮件,有没有任何方法可以像Lets say hash一样。get_key_matchemail您可以使用Hashselect只返回与块匹配的密钥对: h={guest_email:'some_mail',other_key:'1

例如,如何提取具有

散列1 {sample=>{apple=>1,guest\u email=>my_email@example.com}}

散列2 {guest=>{email=>我的_email@example.com}}

假设我想要一个方法,可以从这些散列中提取电子邮件,有没有任何方法可以像Lets say hash一样。get_key_matchemail

您可以使用Hashselect只返回与块匹配的密钥对:

h={guest_email:'some_mail',other_key:'123',apple:1} h、 选择{key,{u value}key=~/email/} =>{来宾电子邮件:“一些邮件”}
我想你需要深入调查。 盒子里没有方法

为此,需要使用递归

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

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
你可以用这个

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


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

你的散列键也总是会改变???是的,基本上如果我从外部来源得到两种类型的散列,那么让我们假设我必须处理这两种类型的散列:kludge:h={:sample=>{:apple=>1,:guest\u email=>'my_email@example.com' }}; h、 到我的_email@example.com.This这对我来说是一个好的开始,当存在匹配项时,我如何只提取没有键的值?你可以选择hash.valueshash.values.select{key,value{key=~/email/}返回[]h.select{key,{u value}key=~/email/}.values