Managing csv strings of unique values

I have a comma separated string of values ​​whose order is not important, but the uniqueness of the values. I want to add values ​​to a string and I get something like

jruby-1.6.7 :009 > ("1,2,3,1".split(",").to_set << "1" << "4").to_a.join ","
  => "1,2,3,4" 

      

which is efficient but looks awful and goes string -> array -> set -> array -> which is no doubt inefficient too. What's an easy way to do this?

+3


source to share


3 answers


you can use | (Union). eg.

[ "1", "2", "3" ,"1"] | [ "1", "4"] 

      

who must return,

["1","2","3","4"]

      



| (the concatenation operator) will not work on strings. so in your case you can use

"1,2,3,4".split(",") | "1,4".split(",")

      

=> ["1", "2", "3", "4"]

+4


source


require 'csv'
str = "1,2,3,1"
ar = CSV.parse(str)
ar << ["1","4"]
p ar.flatten.uniq.to_csv

      



+1


source


[*"1,2,3,1".split(","), "1", "4"].uniq.join ","

      

0


source







All Articles