Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge two lists, and remove duplicates, in ruby/rails?

I have a source object where

class Source

def ==(other)
  return false if self.url == nil || other == nil
  self.url == other.url
end

and i have the following:

def self.merge_internal_and_external_sources(sources=[], external_sources=[])
    (sources + external_sources).uniq
end

I would like to merge the two lists, and start kicking out items from external_sources if they already exist in sources list. I am not sure how to do this eloquently?

I also tried:

sources | external_sources

but this yields a result without the duplicates being removed because of my == comparison want to compare the 'url' attribute internally? For example:

[src1] == [src2] # true
list = [src1] | [src2] 
list.size # 2
like image 991
Kamilski81 Avatar asked Feb 16 '23 09:02

Kamilski81


1 Answers

Another option is to use #uniq method. However, for bare #uniq, the same caveat applies as for #| method: #hash and #eql? are used in sequence to test for identical elements.

However, uniq can take a block, so

(sources + external_sources).uniq &:url

can be applied even if one is lazy to define #hash and #eql? methods for the class in question.

like image 179
house9 Avatar answered Mar 15 '23 06:03

house9