假设我有一个哈希数组
a = [
{'id'=>'1','imageUrl'=>'abc','name'=>'x','age'=>'20'},
{'id'=>'2','imageUrl'=>'efg','name'=>'y','age'=>'30'},
{'id'=>'3','imageUrl'=>'hij','name'=>'z','age'=>'40'}
]
删除密钥'名称'的最快方法是什么?和'年龄'和它们在数组中所有哈希值的对应值?
基本上我该如何删除多个键/值对?
答案 0 :(得分:9)
请尝试以下代码:
a = [
{'id'=>'1','imageUrl'=>'abc','name'=>'x'},
{'id'=>'2','imageUrl'=>'efg','name'=>'y'},
{'id'=>'3','imageUrl'=>'hij','name'=>'z'}
]
a.each { |h| h.delete("name") }
p a # => [{"id"=>"1", "imageUrl"=>"abc"}, {"id"=>"2", "imageUrl"=>"efg"}, {"id"=>"3", "imageUrl"=>"hij"}]
答案 1 :(得分:7)
没有像基准测试那样:
从以上答案中收集:并使用benchmark-ips
require 'benchmark/ips'
def a
[
{'id'=>'1','imageUrl'=>'abc','name'=>'x'},
{'id'=>'2','imageUrl'=>'efg','name'=>'y'},
{'id'=>'3','imageUrl'=>'hij','name'=>'z'}
]
end
Benchmark.ips do |x|
x.report("map w/ except!") do |times|
a.map {|o| o.except!('name') }
end
x.report("each w/ except!") do |times|
a.each {|o| o.except!('name') }
end
x.report("map w/ except") do |times|
a.map {|o| o.except('name') }
end
x.report("each w/ except") do |times|
a.each {|o| o.except('name') }
end
x.report("map w/ delete") do |times|
a.map { |h| h.delete("name") }
end
x.report("each w/ delete") do |times|
a.each { |h| h.delete("name") }
end
x.compare!
end
我得到了以下内容:
Calculating -------------------------------------
map w/ except! 8.438k i/100ms
each w/ except! 8.439k i/100ms
map w/ except 5.242k i/100ms
each w/ except 5.469k i/100ms
map w/ delete 9.840k i/100ms
each w/ delete 9.810k i/100ms
-------------------------------------------------
map w/ except! 1.311B (±25.3%) i/s - 2.994B
each w/ except! 1.360B (±25.2%) i/s - 3.048B
map w/ except 423.818M (±25.8%) i/s - 1.238B
each w/ except 458.859M (±25.7%) i/s - 1.315B
map w/ delete 1.955B (±24.0%) i/s - 3.982B
each w/ delete 2.025B (±23.5%) i/s - 4.033B
Comparison:
each w/ delete: 2024710811.4 i/s
map w/ delete: 1955349074.3 i/s - 1.04x slower
each w/ except!: 1360241861.3 i/s - 1.49x slower
map w/ except!: 1311373772.5 i/s - 1.54x slower
each w/ except: 458859254.7 i/s - 4.41x slower
map w/ except: 423818242.2 i/s - 4.78x slower
使用a.each { |h| h.delete("name") }
是最快的(如评论中所指出的)。
答案 2 :(得分:2)
例如,使用except!
(或except)方法:
a.map {|o| o.except!('name') }
答案 3 :(得分:2)
迭代数组并从每个哈希中删除它:
a = [
{'id'=>'1','imageUrl'=>'abc','name'=>'x'},
{'id'=>'2','imageUrl'=>'efg','name'=>'y'},
{'id'=>'3','imageUrl'=>'hij','name'=>'z'}
]
=> [{"id"=>"1", "imageUrl"=>"abc", "name"=>"x"}, {"id"=>"2", "imageUrl"=>"efg", "name"=>"y"}, {"id"=>"3", "imageUrl"=>"hij", "name"=>"z"}]
a.each do |h|
h.delete("name")
end
=> [{"id"=>"1", "imageUrl"=>"abc"}, {"id"=>"2", "imageUrl"=>"efg"}, {"id"=>"3", "imageUrl"=>"hij"}]