我想按照另一个数组中给出的特定顺序对数组进行排序。
例如:考虑一个数组
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)