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

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

I have a hash like so:

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


        
4条回答
  •  半阙折子戏
    2020-12-16 00:32

    If you're putting this directly into the database, just use validates_uniqueness_of :email in your model. See the documentation for this.

    If you need to remove them from the actual hash before being used then do:

    emails = []  # This is a temporary array, not your results. The results are still in my_array
    my_array.delete_if do |item|
      if emails.include? item[:email]
        true
      else
        emails << item[:email]
        false
      end
    end
    

    UPDATE:

    This will merge the contents of duplicate entries

    merged_list = {}
    my_array.each do |item|
      if merged_list.has_key? item[:email]
        merged_list[item.email].merge! item
      else
        merged_list[item.email] = item
      end
    end
    my_array = merged_list.collect { |k, v| v }
    

提交回复
热议问题