我如何从散列中提取子散列? [英] How do I extract a sub-hash from a hash?

查看:127
本文介绍了我如何从散列中提取子散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个散列:

  h1 = {:a => :A,:b => :B,:c => :C,:d => :D} 

提取这种子哈希的最佳方法是什么?

  h1.extract_subhash(:b,:d,:e,:f)#=> {:b => :B,:d => :D} 
h1#=> {:a => :A,:c => :C}


解决方案

提取的元素但h1保持不变:

  h1 = {:a => :A,:b => :B,:c => :C,:d => :D} 
h2 = h1.select {| key,value | [:b,:d,:e,:f] .include?(key)}#=> {:b =>:B,:d =>:D}
h1 =散列[h1.to_a - h2.to_a]#=> {:a =>:A,:c =>:C}

以将其修补到Hash类中:

$ p $ $ $ $ $ $ $ $ $ def $ extract

h2 = self.select {| key,value | extract.include?(key)}
self.delete_if {| key,value | extract.include?(key)}
h2
end
end

如果你只是想从哈希中删除指定的元素,使用 delete_if

  h1 = {:a => :A,:b => :B,:c => :C,:d => :D} 
h1.delete_if {| key,value | [:b,:d,:e,:f] .include?(key)}#=> {:a =>:A,:c =>:C}
h1#=> {:a =>:A,:c =>:C}


I have a hash:

h1 = {:a => :A, :b => :B, :c => :C, :d => :D}

What is the best way to extract a sub-hash like this?

h1.extract_subhash(:b, :d, :e, :f) # => {:b => :B, :d => :D}
h1 #=> {:a => :A, :c => :C}

解决方案

If you specifically want the method to return the extracted elements but h1 to remain the same:

h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
h2 = h1.select {|key, value| [:b, :d, :e, :f].include?(key) } # => {:b=>:B, :d=>:D} 
h1 = Hash[h1.to_a - h2.to_a] # => {:a=>:A, :c=>:C} 

And if you want to patch that into the Hash class:

class Hash
  def extract_subhash(*extract)
    h2 = self.select{|key, value| extract.include?(key) }
    self.delete_if {|key, value| extract.include?(key) }
    h2
  end
end

If you just want to remove the specified elements from the hash, that is much easier using delete_if.

h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
h1.delete_if {|key, value| [:b, :d, :e, :f].include?(key) } # => {:a=>:A, :c=>:C} 
h1  # => {:a=>:A, :c=>:C} 

这篇关于我如何从散列中提取子散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆