Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique on an array of hashes based on value

Tags:

ruby

I feel like this could be improved (a common feeling in ruby). I'm trying to uniq an array of hashes based on value. In this example, I want the colors of the elements. Moss and snow are impostors.

# remove unique array of hashes based on a hash value  a = [   { :color => "blue", :name => "water" },   { :color => "red", :name => "fire" },   { :color => "white", :name => "wind" },   { :color => "green", :name => "earth" },   { :color => "green", :name => "moss" },   { :color => "white", :name => "snow" } ]  # remove moss and snow uniques = [] a.each_with_index do |r, i|   colors = uniques.collect {|e| e[:color]}    if !colors.include? r[:color]     uniques.push r   else     a[i] = nil   end end  a.compact!  puts a 

This will print

{:color=>"blue", :name=>"water"} {:color=>"red", :name=>"fire"} {:color=>"white", :name=>"wind"} {:color=>"green", :name=>"earth"} 

Which is "correct" however I feel like this is excessive. My experience with .map .inject is limited and those advanced techniques elude me. If someone could re-factor this, it might help me understand another terse technique.

like image 703
squarism Avatar asked Jan 30 '11 04:01

squarism


1 Answers

In Ruby 1.9, try the following

a.uniq! {|e| e[:color] } 
like image 54
Steve Wilhelm Avatar answered Oct 14 '22 00:10

Steve Wilhelm