gpt4 book ai didi

ruby - 如何按特定顺序对 Ruby 中的数组进行排序?

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:46 24 4
gpt4 key购买 nike

我想按照另一个数组中给定的特定顺序对数组进行排序。

EX:考虑一个数组

a=["one", "two", "three"]
b=["two", "one", "three"]

现在我想按照 'b' 的顺序对数组 'a' 进行排序,即

a.each do |t|
# It should be in the order of 'b'
puts t
end

所以输出应该是

two
one
three

有什么建议吗?

最佳答案

Array#sort_by 就是您所追求的。

a.sort_by do |element|
b.index(element)
end

响应评论的更具扩展性的版本:

a=["one", "two", "three"]
b=["two", "one", "three"]

lookup = {}
b.each_with_index do |item, index|
lookup[item] = index
end

a.sort_by do |item|
lookup.fetch(item)
end

关于ruby - 如何按特定顺序对 Ruby 中的数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4283295/

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