sgi
sgi

Reputation: 2032

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

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

EX: consider an array

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

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

So the output should be

two
one 
three 

Any suggestions?

Upvotes: 32

Views: 16949

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81450

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

Upvotes: 58

Nakilon
Nakilon

Reputation: 35054

If b includes all elements of a and if elements are unique, then:

puts b & a

Upvotes: 12

Chirantan
Chirantan

Reputation: 15634

Assuming a is to be sorted with respect to order of elements in b

sorted_a = 
a.sort do |e1, e2|
  b.index(e1) <=> b.index(e2)
end

I normally use this to sort error messages in ActiveRecord in the order of appearance of fields on the form.

Upvotes: 10

Related Questions