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.
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"]
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