code_junkie

How do I get the unique elements from an array of hashes in Ruby?

Nov 11th, 2011
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. a = [{:a => 1},{:a => 2}, {:a => 1}]
  2. a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}]
  3.  
  4. [{:a => 1}, {:a => 2}]
  5.  
  6. a = [{:a => 1},{:a => 2}, {:a => 1}]
  7. a.inject([]) { |result,h| result << h unless result.include?(h); result }
  8.  
  9. [{:a=>1}, {:a=>2}]
  10.  
  11. [{:x=>1},{:x=>2},{:x=>3},{:x=>2},{:x=>1}]
  12.  
  13. [{:x=>1}, {:x=>1}, {:x=>2}, {:x=>2}, {:x=>3}]
  14.  
  15. your_array.inject([]) do |result,item|
  16. result << item if !result.last||result.last[:x]!=item[:x]
  17. result
  18. end
  19.  
  20. test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]}
  21.  
  22. test=[]
  23. 1000.times {test<<{:x=>rand}}
  24.  
  25. Benchmark.bmbm do |bm|
  26. bm.report("sorting: ") do
  27. test.sort_by {|t| t[:x]}.inject([]) {|r,h| r<<h if !r.last||r.last[:x]!=h[:x]; r}
  28. end
  29. bm.report("inject: ") {test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]} }
  30. end
  31.  
  32. Rehearsal ---------------------------------------------
  33. sorting: 0.010000 0.000000 0.010000 ( 0.005633)
  34. inject: 0.470000 0.140000 0.610000 ( 0.621973)
  35. ------------------------------------ total: 0.620000sec
  36.  
  37. user system total real
  38. sorting: 0.010000 0.000000 0.010000 ( 0.003839)
  39. inject: 0.480000 0.130000 0.610000 ( 0.612438)
  40.  
  41. [{:a=>1}, {:a=>2}, {:a=>1}].uniq
  42. #=> [{:a=>1}, {:a=>2}]
  43.  
  44. a.map {|h| h.to_a[0]}.uniq.map {|k,v| {k => v}}
  45.  
  46. [[:a, 1], [:a, 2], [:a, 1]]
  47.  
  48. [[:a, 1], [:a, 2]]
Add Comment
Please, Sign In to add comment