我需要比較此處宣告的 2 個陣列以回傳僅存在于 filters_apps 陣列中的記錄。我正在使用previous_apps 陣列的內容來查看filtered_apps 陣列中是否存在記錄中的ID。我會將結果輸出到 CSV 并將兩個陣列中存在的記錄顯示到控制臺。
我的問題是:如何獲取僅存在于過濾應用程式中的記錄?對我來說最簡單的是將這些唯??一記錄放入一個新陣列中以在 csv 上使用。
start_date = Date.parse("2022-02-05")
end_date = Date.parse("2022-05-17")
valid_year = start_date.year
dupe_apps = []
uniq_apps = []
# Finding applications that meet my criteria:
filtered_apps = FinancialAssistance::Application.where(
:is_requesting_info_in_mail => true,
:aasm_state => "determined",
:submitted_at => {
"$exists" => true,
"$gte" => start_date,
"$lte" => end_date })
# Finding applications that I want to compare against filtered_apps
previous_apps = FinancialAssistance::Application.where(
is_requesting_info_in_mail: true,
:submitted_at => {
"$exists" => true,
"$gte" => valid_year })
# I'm using this to pull the ID that I'm using for comparison just to make the comparison lighter by only storing the family_id
previous_apps.each do |y|
previous_apps_array << y.family_id
end
# This is where I'm doing my comparison and it is not working.
filtered_apps.each do |app|
if app.family_id.in?(previous_apps_array) == false
then @non_dupe_apps << app
else "No duplicate found for application #{app.hbx_id}"
end
end
end
那么我在最后一個代碼部分做錯了什么?
uj5u.com熱心網友回復:
讓我們首先檢查您的原始方法(我修復了縮進以使其更清晰)。它有很多問題:
filtered_apps.each do |app|
if app.family_id.in?(previous_apps_array) == false
# Where is "@non_dupe_apps" declared? It isn't anywhere in your example...
# Also, "then" is not necessary unless you want a one-line if-statement
then @non_dupe_apps << app
# This doesn't do anything, it's just a string
# You need to use "p" or "puts" to output something to the console
# Note that the "else" is also only triggered when duplicates WERE found...
else "No duplicate found for application #{app.hbx_id}"
end # Extra "end" here, this will mess things up
end
end
此外,您還沒有previous_apps_array在示例中的任何地方宣告,您只是突然開始添加它。
在 Ruby 中獲取 2 個陣列之間的差異非常容易:只需使用-!
uniq_apps = filtered_apps - previous_apps
您也可以對 ActiveRecord 結果執行此操作,因為它們只是 ActiveRecord 物件的陣列。family_id但是,如果您特別需要使用該列比較結果,這將無濟于事。
提示:pluck如果您不需要存盤有關這些物件的任何其他資料,則最好使用該方法從 ActiveRecord 查詢中獲取僅包含特定列/列的陣列,因為它發生在資料庫查詢級別。您只能在結果中獲得一組值,而不是完整的物件。
# Querying straight from the database
# This is what I would recommend, but it doesn't print the values of duplicate records
uniq_apps = filtered_apps.where.not(family_id: previous_apps.pluck(:family_id))
我強烈建議您至少熟悉基本陣列方法filter,map并且可能不熟悉這些方法。reduce他們使這樣的事情變得更容易。一個非常簡單的示例,與您在問題中使用filter2 個陣列解釋的內容類似,如下所示:
arr = [1, 2, 3]
full_arr = [1, 2, 3, 4, 5]
unique_numbers = full_arr.filter do |num|
if arr.include? num
puts "Duplicates were found for #{num}"
false
else
true
end
end
# Duplicates were found for 1
# Duplicates were found for 2
# Duplicates were found for 3
=> [4, 5]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/495737.html
