【发布时间】:2020-02-01 18:04:53
【问题描述】:
我有两个不同的数组,我试图避免重复。
我尝试通过 arr1 循环而不是通过 arr2 循环,当匹配时它应该从 arr1 中删除值
def gmail_interviews
arr1 = []
arr2 = []
arr1 = [{"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
"to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
"snippet"=>"interview booked"},
{"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
"to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
"snippet"=>"Interview booked for tomorrow"}]
arr2 = [{"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
"to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
"snippet"=>"interview booked"},
{"from"=>"chinedu abalogu <chineduabalogu@yahoo.com>",
"to"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"date"=>"chinedu abalogu <chineduabalogu@gmail.com>",
"subject"=>[{"name"=>"From", "value"=>"chinedu abalogu <chineduabalogu@yahoo.com>"}],
"snippet"=>"Interview booked for tomorrow"}]
arr1.each_with_index do |id, index|
if !arr2.empty?
arr2.each_with_index do |i, ind|
if i == id
puts "Cant save duplicated message to db\n #{id}"
arr1.delete_at(index)
end
end
end
end
render json: arr.as_json
end
从我的代码中,它会为 arr2 循环一次和两次 arr1 并停止而不是在两个数组中循环两次,因为它们都包含 2 个值计数
基本上它会找到 arr1[0] 的重复项,然后删除它不会循环遍历 arr1[1]
返回值应为 nil 或空,因为两个数组具有相同的值。请问我缺少什么?
【问题讨论】:
-
最终输出想要什么,一个没有重复的数组?如果是这样,那么
(arr1 + arr2).uniq
标签: ruby-on-rails arrays ruby