Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- a = [{:a => 1},{:a => 2}, {:a => 1}]
- a.uniq # => [{:a => 1}, {:a => 2}, {:a => 1}]
- [{:a => 1}, {:a => 2}]
- a = [{:a => 1},{:a => 2}, {:a => 1}]
- a.inject([]) { |result,h| result << h unless result.include?(h); result }
- [{:a=>1}, {:a=>2}]
- [{:x=>1},{:x=>2},{:x=>3},{:x=>2},{:x=>1}]
- [{:x=>1}, {:x=>1}, {:x=>2}, {:x=>2}, {:x=>3}]
- your_array.inject([]) do |result,item|
- result << item if !result.last||result.last[:x]!=item[:x]
- result
- end
- test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]}
- test=[]
- 1000.times {test<<{:x=>rand}}
- Benchmark.bmbm do |bm|
- bm.report("sorting: ") do
- test.sort_by {|t| t[:x]}.inject([]) {|r,h| r<<h if !r.last||r.last[:x]!=h[:x]; r}
- end
- bm.report("inject: ") {test.inject([]) {|r,h| r<<h unless r.find {|t| t[:x]==h[:x]}; r}.sort_by {|t| t[:x]} }
- end
- 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)
- [{:a=>1}, {:a=>2}, {:a=>1}].uniq
- #=> [{:a=>1}, {:a=>2}]
- a.map {|h| h.to_a[0]}.uniq.map {|k,v| {k => v}}
- [[:a, 1], [:a, 2], [:a, 1]]
- [[:a, 1], [:a, 2]]
Add Comment
Please, Sign In to add comment