我有一串用逗号分隔的值,其顺序并不重要,但值的唯一性是。我想为字符串添加值,最后我会得到类似
的内容jruby-1.6.7 :009 > ("1,2,3,1".split(",").to_set << "1" << "4").to_a.join ","
=> "1,2,3,4"
这是有效的,但看起来很糟糕并且变成了字符串 - &gt;数组 - &gt;集 - &gt;数组 - &gt;字符串,这无疑也无效。这样做的简单方法是什么?
答案 0 :(得分:4)
你可以使用| (联盟)运营商。 e.g。
[ "1", "2", "3" ,"1"] | [ "1", "4"]
将返回,
["1","2","3","4"]
| (联盟运营商)不会在字符串上工作。所以在你的情况下,你可以使用
"1,2,3,4".split(",") | "1,4".split(",")
=&GT; [“1”,“2”,“3”,“4”]
答案 1 :(得分:1)
require 'csv'
str = "1,2,3,1"
ar = CSV.parse(str)
ar << ["1","4"]
p ar.flatten.uniq.to_csv
答案 2 :(得分:0)
[*"1,2,3,1".split(","), "1", "4"].uniq.join ","