Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 313
sgi Avatar asked Nov 26 '10 07:11

sgi


People also ask

How can you sort an array Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.

Can you sort elements in a Ruby hash object?

Sorting Hashes in RubyTo sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.

Can we sort elements in array?

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.


2 Answers

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 
like image 80
Andrew Grimm Avatar answered Sep 28 '22 05:09

Andrew Grimm


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

puts b & a 
like image 26
Nakilon Avatar answered Sep 28 '22 03:09

Nakilon