Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.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 从哈希数组中删除除一个副本以外的所有副本_Ruby_Arrays - Fatal编程技术网

Ruby 从哈希数组中删除除一个副本以外的所有副本

Ruby 从哈希数组中删除除一个副本以外的所有副本,ruby,arrays,Ruby,Arrays,我有这样一个哈希数组: [ { :color => 'red', :animal => 'dog' }, { :color => 'blue', :animal => 'cat' }, { :color => 'yellow', :animal => 'frog' }, { :color => 'red', :animal => 'cat' }, { :color => 'red', :animal => 'mous

我有这样一个哈希数组:

[
  { :color => 'red', :animal => 'dog' },
  { :color => 'blue', :animal => 'cat' },
  { :color => 'yellow', :animal => 'frog' },
  { :color => 'red', :animal => 'cat' },
  { :color => 'red', :animal => 'mouse' }
]
[
  { :color => 'blue', :animal => 'cat' },
  { :color => 'yellow', :animal => 'frog' },
  { :color => 'red', :animal => 'mouse' }
]
我想做的是根据其中一个键删除除一个之外的所有副本

因此,在本例中,我想删除
color
red
的所有项目,只有一个除外。不管是哪一个

最终输出如下:

[
  { :color => 'red', :animal => 'dog' },
  { :color => 'blue', :animal => 'cat' },
  { :color => 'yellow', :animal => 'frog' },
  { :color => 'red', :animal => 'cat' },
  { :color => 'red', :animal => 'mouse' }
]
[
  { :color => 'blue', :animal => 'cat' },
  { :color => 'yellow', :animal => 'frog' },
  { :color => 'red', :animal => 'mouse' }
]

同样,在删除重复项时,要保留的项并不重要。

.groupby{x | x[:color]}.values.map(&:first)


.inject({}){xs,x|xs[x[:color]]=x;xs}.values
.group_by{x | x[:color]}.values.map(&:first)


.inject({}){xs,x{xs[x[:color]]=x;xs}.values

实现这一点的另一种方法是

.uniq { |h| h[:color] }
=>[{:color=>“红色”,:动物=>“狗”},{:color=>“蓝色”, :animal=>“cat”},{:color=>“yellow”,:animal=>“frog”}]


正如@Victor所建议的,这是针对ruby 1.9.2+

实现这一点的另一种方法是

.uniq { |h| h[:color] }
=>[{:color=>“红色”,:动物=>“狗”},{:color=>“蓝色”, :animal=>“cat”},{:color=>“yellow”,:animal=>“frog”}]

正如@Victor所建议的,这是针对ruby 1.9.2+

1.9.2+(针对那些坚持使用1.8.7的可怜人)1.9.2+(针对那些坚持使用1.8.7的可怜人)