如何将数组的元素添加到另一个数组并删除重复项

时间:2015-07-25 14:52:14

标签: ruby-on-rails arrays ruby

我试图在具有特定格式的rails上的ruby中创建一个json文件:

{"nodes":["1","2","3"],"edges":[["1","3"],["2","3"],["2","1"]]}

我的模型中有一个方法如下:

def self.joinup(id)
  c = Challenge.find(id)
  result={}
  user_ids  =  c.users.pluck(:id)
  result["nodes"] = user_ids.collect(&:to_s)
  result["edges"] = Relationship.where(follower_id: user_ids).map{|h| [h.follower_id.to_s, h.followed_id.to_s]}
  result["nodes"] = result["nodes"]|result["edges"]
  result
 end

这会产生:

{"nodes":["1","2","3","3","3"["4","5"],["5","6"]],"edges":[["4","5"],["5","6"]]}

而我想要的是:

{"nodes":["1","2","3","4","5","6"],"edges":[["4","5"],["5","6"]]}

2 个答案:

答案 0 :(得分:5)

在rails中你可以使用数组方法 flatten ,它返回一个包含一维的数组,如下所示

.top_menu

之后,您可以使用 uniq 方法,它返回数组中的所有不同值,因此这将返回此结果

array = ["1", "2", "3", ["2", "3", "4"], "5"]
array.flatten #=> ["1", "2", "3", "2", "3", "4", "5"]

此外,此方法可以与bang(!)运算符一起使用,它使用返回值更改原始数组,因此它将是这样的

array.flatten.uniq #=> ["1", "2", "3", "4", "5"]

希望它有所帮助:D

答案 1 :(得分:0)

您合并了此行中static void Main(string[] args) { String sentence = "TAG123_Sample"; String pattern=@"TAG[^\d]_"; String replacement = ""; Regex r = new Regex(pattern); String res = r.Replace(sentence,replacement); Console.WriteLine(res); Console.ReadLine(); } 中的内容:

result["edges"]

之后,您可以首先result["nodes"] = result["nodes"]|result["edges"] 数组,然后flatten

uniq