How can I more elegantly remove duplicate items across all elements of a Ruby Array? -



How can I more elegantly remove duplicate items across all elements of a Ruby Array? -

i want remove duplicate items within array object. it's best explain example.

i have next array

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

i want method clean removing duplicate items within elements in array , homecoming array has 1 element each unique item.

so here's method i've written this:

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

so when phone call entries.clean_up next result:

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

this result want there more elegant way in ruby?

split splits on whitespace default (assuming of course of study haven't done insane changing $;). want split each string , flatten results 1 list, time want "do x each element , flatten" want utilize flat_map. putting yields:

self.flat_map(&:split).uniq

if want split on spaces or don't want depend on sanity, could:

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

or similar.

ruby arrays

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -