Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to sort an array of numbers and string in ruby?

Input :

arr = [4,2,'b',5,'c','a',7]

Output:

[2,4,5,7,'a','b','c']

I can think of this :

int_arr = arr.select {|x| x.instance_of?(Integer)}.sort
str_arr = arr.select {|x| x.instance_of?(String)}.sort

int_arr + str_arr

Please suggest a efficient way to do it.

like image 927
vikas95prasad Avatar asked Nov 13 '19 18:11

vikas95prasad


1 Answers

One way is to partition your array by those elements being Integer, to make sure they remain first and then sort the elements of each array:

[4,2,'b',5,'c','a',7].partition { |e| e.is_a?(Integer) }.flat_map(&:sort)
# [2, 4, 5, 7, "a", "b", "c"]
like image 60
Sebastian Palma Avatar answered Sep 18 '22 12:09

Sebastian Palma