gpt4 book ai didi

ruby-on-rails - 根据排序值数组对哈希数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:29 25 4
gpt4 key购买 nike

我有一个散列数组,如下所示:

user_quizzes = [{:id => 3897, :quiz_id => 1793, :user_id => 252}, {:id => 3897, :quiz_id => 1793, :user_id => 475}, {:id => 3897, :quiz_id => 1793, :user_id => 880}, {:id => 3897, :quiz_id => 1793, :user_id => 881}, {:id => 3897, :quiz_id => 1793, :user_id => 882}, {:id => 3897, :quiz_id => 1793, :user_id => 883}, {:id => 3897, :quiz_id => 1793, :user_id => 884}]

此外,根据特定条件,我从相同的散列中获取“user_id”键的值并对其进行排序,下面给出了相同的数组:

sorted_user_ids = [880, 881, 882, 883, 884, 475, 252]

现在,我需要根据 sorted_user_ids 数组中 user_id 的顺序重新排列 user_quizzes

谁能帮我解决这个问题。 :)

最佳答案

使用 Enumerable#sort_byArray#sort_by! ,您可以指定将用于比较的键:

user_quizzes = [
{:id => 3897, :quiz_id => 1793, :user_id => 252},
{:id => 3897, :quiz_id => 1793, :user_id => 475},
{:id => 3897, :quiz_id => 1793, :user_id => 880},
{:id => 3897, :quiz_id => 1793, :user_id => 881},
{:id => 3897, :quiz_id => 1793, :user_id => 882},
{:id => 3897, :quiz_id => 1793, :user_id => 883},
{:id => 3897, :quiz_id => 1793, :user_id => 884}
]
sorted_user_ids = [880, 881, 882, 883, 884, 475, 252]
user_quizzes.sort_by { |x| sorted_user_ids.index(x[:user_id]) }
# => [{:id=>3897, :quiz_id=>1793, :user_id=>880},
# {:id=>3897, :quiz_id=>1793, :user_id=>881},
# {:id=>3897, :quiz_id=>1793, :user_id=>882},
# {:id=>3897, :quiz_id=>1793, :user_id=>883},
# {:id=>3897, :quiz_id=>1793, :user_id=>884},
# {:id=>3897, :quiz_id=>1793, :user_id=>475},
# {:id=>3897, :quiz_id=>1793, :user_id=>252}]

旁注:如果数组很大,sorted_user_ids.index(x[:user_id]) 可能成为瓶颈(重复 O(n) 操作)。

在这种情况下构建一个将 user_id 映射到订单的散列:

sorted_user_ids = [880, 881, 882, 883, 884, 475, 252]
order = Hash[sorted_user_ids.each_with_index.to_a]
# => {880=>0, 881=>1, 882=>2, 883=>3, 884=>4, 475=>5, 252=>6}
user_quizzes.sort_by { |x| order[x[:user_id]] }
# => same as above.

关于ruby-on-rails - 根据排序值数组对哈希数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com