I have an array of hashes, and I want the unique values out of it. Calling Array.uniq doesn\'t give me what I expect.
a = [{:a => 1},{:a =&g
I've had a similar situation, but hashes had keys. I used sorting method.
What I mean:
you have an array:
[{:x=>1},{:x=>2},{:x=>3},{:x=>2},{:x=>1}]
you sort it (#sort_by {|t| t[:x]}) and get this:
[{:x=>1}, {:x=>1}, {:x=>2}, {:x=>2}, {:x=>3}]
now a bit modified version of answer by Aaaron Hinni:
your_array.inject([]) do |result,item|
result << item if !result.last||result.last[:x]!=item[:x]
result
end
I've also tried:
test.inject([]) {|r,h| r<
but it's very slow. here is my benchmark:
test=[]
1000.times {test<<{:x=>rand}}
Benchmark.bmbm do |bm|
bm.report("sorting: ") do
test.sort_by {|t| t[:x]}.inject([]) {|r,h| r<
results:
Rehearsal ---------------------------------------------
sorting: 0.010000 0.000000 0.010000 ( 0.005633)
inject: 0.470000 0.140000 0.610000 ( 0.621973)
------------------------------------ total: 0.620000sec
user system total real
sorting: 0.010000 0.000000 0.010000 ( 0.003839)
inject: 0.480000 0.130000 0.610000 ( 0.612438)