如何将 Ruby 中的数组按特定顺序排序? [英] How to sort an array in Ruby to a particular order?

查看:57
本文介绍了如何将 Ruby 中的数组按特定顺序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to sort an array in particular order given in another array.

EX:考虑一个数组

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

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

Now I want to sort array 'a' in the order of 'b', i.e

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

所以输出应该是

two
one 
three 

有什么建议吗?

推荐答案

Array#sort_by 正是您所追求的.

Array#sort_by is what you're after.

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

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

More scalable version in response to comment:

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 中的数组按特定顺序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆