How to sort an array in Ruby to a particular order?

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

Leave a Comment