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?
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.
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.
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.
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
If b
includes all elements of a
and if elements are unique, then:
puts b & a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With