How to remove duplicates in a hash in Ruby on Rails?

后端 未结 4 1646
眼角桃花
眼角桃花 2020-12-15 23:39

I have a hash like so:

[
  {
    :lname => \"Brown\",
    :email => \"james@intuit.com\",
    :fname => \"James\"
  },
  {
    :lname => nil,
            


        
4条回答
  •  -上瘾入骨i
    2020-12-16 00:18

    Ok, this (delete duplicates) is what you asked for:

    a.sort_by { |e| e[:email] }.inject([]) { |m,e| m.last.nil? ? [e] : m.last[:email] == e[:email] ? m : m << e }
    

    But I think this (merge values) is what you want:

    a.sort_by { |e| e[:email] }.inject([]) { |m,e| m.last.nil? ? [e] : m.last[:email] == e[:email] ? (m.last.merge!(e) { |k,o,n| o || n }; m) : m << e }
    

    Perhaps I'm stretching the one-liner idea a bit unreasonably, so with different formatting and a test case:

    Aiko:so ross$ cat mergedups
    require 'pp'
    
    a = [{:fname=>"James", :lname=>"Brown", :email=>"james@intuit.com"},
         {:fname=>nil,     :lname=>nil,     :email=>"brad@intuit.com"},
         {:fname=>"Brad",  :lname=>"Smith", :email=>"brad@intuit.com"},
         {:fname=>nil,     :lname=>nil,     :email=>"brad@intuit.com"},
         {:fname=>"Brad",  :lname=>"Smith", :email=>"brad@intuit.com"},
         {:fname=>"Brad",  :lname=>"Smith", :email=>"brad@intuit.com"}]
    
    pp(
      a.sort_by { |e| e[:email] }.inject([]) do |m,e|
        m.last.nil? ? [e] :
          m.last[:email] == e[:email] ? (m.last.merge!(e) { |k,o,n| o || n }; m) :
            m << e
      end
    )
    Aiko:so ross$ ruby mergedups
    [{:email=>"brad@intuit.com", :fname=>"Brad", :lname=>"Smith"},
     {:email=>"james@intuit.com", :fname=>"James", :lname=>"Brown"}]
    

提交回复
热议问题