我有一个哈希:
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}
答案 0 :(得分:121)
ActiveSupport
,至少从2.3.8开始,提供了四种方便的方法:#slice
,#except
及其破坏性对应方式:#slice!
和#except!
。在其他答案中提到了它们,但要在一个地方加以总结:
x = {a: 1, b: 2, c: 3, d: 4}
# => {:a=>1, :b=>2, :c=>3, :d=>4}
x.slice(:a, :b)
# => {:a=>1, :b=>2}
x
# => {:a=>1, :b=>2, :c=>3, :d=>4}
x.except(:a, :b)
# => {:c=>3, :d=>4}
x
# => {:a=>1, :b=>2, :c=>3, :d=>4}
注意bang方法的返回值。它们不仅会定制现有的哈希值,还会返回已删除(未保留)的条目。 Hash#except!
最适合问题中给出的示例:
x = {a: 1, b: 2, c: 3, d: 4}
# => {:a=>1, :b=>2, :c=>3, :d=>4}
x.except!(:c, :d)
# => {:a=>1, :b=>2}
x
# => {:a=>1, :b=>2}
ActiveSupport
不需要整个Rails,非常轻量级。事实上,很多非rails gems都依赖于它,所以很可能你已经在Gemfile.lock中拥有它了。无需自己扩展Hash类。
答案 1 :(得分:54)
如果您特别希望方法返回提取的元素,但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 = Hash[h1.to_a - h2.to_a] # => {:a=>:A, :c=>:C}
如果你想将其修补到Hash类中:
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
如果您只想从哈希中删除指定的元素,使用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}
答案 2 :(得分:26)
如果您使用rails ,Hash#slice即可。
{:a => :A, :b => :B, :c => :C, :d => :D}.slice(:a, :c)
# => {:a => :A, :c => :C}
如果您不使用导轨,Hash#values_at will return the values in the same order as you asked them,那么您可以这样做:
def slice(hash, *keys)
Hash[ [keys, hash.values_at(*keys)].transpose]
end
def except(hash, *keys)
desired_keys = hash.keys - keys
Hash[ [desired_keys, hash.values_at(*desired_keys)].transpose]
end
例如:
slice({foo: 'bar', 'bar' => 'foo', 2 => 'two'}, 'bar', 2)
# => {'bar' => 'foo', 2 => 'two'}
except({foo: 'bar', 'bar' => 'foo', 2 => 'two'}, 'bar', 2)
# => {:foo => 'bar'}
说明:
{:a => 1, :b => 2, :c => 3}
我们需要{:a => 1, :b => 2}
hash = {:a => 1, :b => 2, :c => 3}
keys = [:a, :b]
values = hash.values_at(*keys) #=> [1, 2]
transposed_matrix =[keys, values].transpose #=> [[:a, 1], [:b, 2]]
Hash[transposed_matrix] #=> {:a => 1, :b => 2}
如果你觉得猴子补丁是要走的路,那就是你想要的:
module MyExtension
module Hash
def slice(*keys)
::Hash[[keys, self.values_at(*keys)].transpose]
end
def except(*keys)
desired_keys = self.keys - keys
::Hash[[desired_keys, self.values_at(*desired_keys)].transpose]
end
end
end
Hash.include MyExtension::Hash
答案 3 :(得分:14)
h = { a: 100, b: 200, c: 300 }
h.slice(:a) #=> {:a=>100}
h.slice(:b, :c, :d) #=> {:b=>200, :c=>300}
答案 4 :(得分:5)
module HashExtensions
def subhash(*keys)
keys = keys.select { |k| key?(k) }
Hash[keys.zip(values_at(*keys))]
end
end
Hash.send(:include, HashExtensions)
{:a => :A, :b => :B, :c => :C, :d => :D}.subhash(:a) # => {:a => :A}
答案 5 :(得分:4)
您可以使用在ActiveSupport核心扩展中提供的切片!(*键)
initial_hash = {:a => 1, :b => 2, :c => 3, :d => 4}
extracted_slice = initial_hash.slice!(:a, :c)
initial_hash现在是
{:b => 2, :d =>4}
extract_slide现在是
{:a => 1, :c =>3}
您可以查看slice.rb in ActiveSupport 3.1.3
答案 6 :(得分:3)
h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
keys = [:b, :d, :e, :f]
h2 = (h1.keys & keys).each_with_object({}) { |k,h| h.update(k=>h1.delete(k)) }
#=> {:b => :B, :d => :D}
h1
#=> {:a => :A, :c => :C}
答案 7 :(得分:2)
class Hash
def extract(*keys)
key_index = Hash[keys.map{ |k| [k, true] }] # depends on the size of keys
partition{ |k, v| key_index.has_key?(k) }.map{ |group| Hash[group] }
end
end
h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
h2, h1 = h1.extract(:b, :d, :e, :f)
答案 8 :(得分:1)
此代码将您要求的功能注入Hash类:
class Hash
def extract_subhash! *keys
to_keep = self.keys.to_a - keys
to_delete = Hash[self.select{|k,v| !to_keep.include? k}]
self.delete_if {|k,v| !to_keep.include? k}
to_delete
end
end
并生成您提供的结果:
h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
p h1.extract_subhash!(:b, :d, :e, :f) # => {b => :B, :d => :D}
p h1 #=> {:a => :A, :c => :C}
注意:此方法实际上返回提取的键/值。
答案 9 :(得分:1)
delete_if
和keep_if
都是Ruby核心的一部分。在这里,您无需修补Hash
类型就可以实现所需的功能。
h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
h2 = h1.clone
p h1.keep_if { |key| [:b, :d, :e, :f].include?(key) } # => {:b => :B, :d => :D}
p h2.delete_if { |key, value| [:b, :d, :e, :f].include?(key) } #=> {:a => :A, :c => :C}
有关更多信息,请查看文档中的以下链接:
答案 10 :(得分:1)
以下是建议方法的快速性能比较,#select
似乎是最快的
k = 1_000_000
Benchmark.bmbm do |x|
x.report('select') { k.times { {a: 1, b: 2, c: 3}.select { |k, _v| [:a, :b].include?(k) } } }
x.report('hash transpose') { k.times { Hash[ [[:a, :b], {a: 1, b: 2, c: 3}.fetch_values(:a, :b)].transpose ] } }
x.report('slice') { k.times { {a: 1, b: 2, c: 3}.slice(:a, :b) } }
end
Rehearsal --------------------------------------------------
select 1.640000 0.010000 1.650000 ( 1.651426)
hash transpose 1.720000 0.010000 1.730000 ( 1.729950)
slice 1.740000 0.010000 1.750000 ( 1.748204)
----------------------------------------- total: 5.130000sec
user system total real
select 1.670000 0.010000 1.680000 ( 1.683415)
hash transpose 1.680000 0.010000 1.690000 ( 1.688110)
slice 1.800000 0.010000 1.810000 ( 1.816215)
细化将如下所示:
module CoreExtensions
module Extractable
refine Hash do
def extract(*keys)
select { |k, _v| keys.include?(k) }
end
end
end
end
使用它:
using ::CoreExtensions::Extractable
{ a: 1, b: 2, c: 3 }.extract(:a, :b)
答案 11 :(得分:1)
如果你使用rails,使用Hash.except
可能会很方便h = {a:1, b:2}
h1 = h.except(:a) # {b:2}
答案 12 :(得分:0)
这是一个功能性解决方案,如果你没有在Ruby 2.5上运行,并且你不想通过添加新方法来污染你的Hash类,那么它将非常有用:
slice_hash = -> keys, hash { hash.select { |k, _v| keys.include?(k) } }.curry
然后你甚至可以在嵌套的哈希中应用它:
my_hash = [{name: "Joe", age: 34}, {name: "Amy", age: 55}]
my_hash.map(&slice_hash.([:name]))
# => [{:name=>"Joe"}, {:name=>"Amy"}]
答案 13 :(得分:0)
正如其他人提到的那样,Ruby 2.5添加了Hash#slice方法。
Rails 5.2.0beta1还添加了它自己的Hash#slice版本,以填充使用早期版本Ruby的框架用户的功能。 https://github.com/rails/rails/commit/01ae39660243bc5f0a986e20f9c9bff312b1b5f8
如果出于某种原因希望实现自己的实现,那么这也是一个不错的选择:
def slice(*keys)
keys.each_with_object(Hash.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
end unless method_defined?(:slice)
答案 14 :(得分:0)
只是slice方法的补充,如果要与原始哈希分开的subhash键是动态的,您可以这样做,
slice(*dynamic_keys) # dynamic_keys should be an array type
答案 15 :(得分:0)
我们可以通过仅在我们要提取的键上循环并仅检查键是否存在然后提取它来完成它。
class Hash
def extract(*keys)
extracted_hash = {}
keys.each{|key| extracted_hash[key] = self.delete(key) if self.has_key?(key)}
extracted_hash
end
end
h1 = {:a => :A, :b => :B, :c => :C, :d => :D}
h2 = h1.extract(:b, :d, :e, :f)
答案 16 :(得分:0)