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.
In Ruby 1.9, try the following
a.uniq! {|e| e[:color] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With