How can I more elegantly remove duplicate elements in all Ruby Array elements?

I want to remove duplicate elements inside an Array object. Best explained by example.

I have the following Array

 entries = ["abc", "ab", "c", "cd"] 

I need a method that will clear it by removing duplicate elements from elements in an Array and return an Array that has one element for each unique element.

So here is this method that I wrote for this:

 class Array def clean_up() self.join(" ").split(" ").uniq end end 

So, now when I call entries.clean_up , I get the following as a result:

 ["a", "b", "c", "d"] 

This is exactly the result I want, but is there a more elegant way to do this in Ruby?

+6
source share
1 answer

split into spaces by default (assuming you haven't done anything crazy like changing $; ). You want to split each line and smooth the results into one list, every time you want to "make X for each element and smooth", you want to use flat_map . Combining them, we get:

 self.flat_map(&:split).uniq 

If you want to separate only spaces or do not want to depend on sanity, you can:

 self.flat_map { |s| s.split(' ') }.uniq 

or similar.

+1
source

Source: https://habr.com/ru/post/976613/


All Articles