Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Ruby array with mixed Strings and Fixnums

I need to sort a mixed array in Ruby. It has Fixnums and Strings

ar = [1, "cool", 3, "story", 4, "bro"]

I want the Fixnums to take precedence over the strings and don't care what order the strings are in.

ar = [1,3,4,"cool","story","bro"]

I've tried writing a method for class Array

Class Array
  def mixed_sort
    self.sort do |a,b|
      if a.class == Fixnum and b.class != a.class
        -1
      else
        a <=> b
      end
    end
  end
end

I thought I might just pass a block to the Array#sort method. However this method still throws an error before hitting the block

[1] pry(main)> [1, "11", '12', 3, "cool"].mixed_sort
ArgumentError: comparison of String with 3 failed
from /config/initializers/extensions/array.rb:3:in `sort'
like image 792
kevzettler Avatar asked Dec 27 '25 15:12

kevzettler


1 Answers

I would do as below using Enumerable#grep:

ar = [1, "cool", 3, "story", 4, "bro"]
ar.grep(Fixnum).sort + ar.grep(String)
# => [1, 3, 4, "cool", "story", "bro"]

If you want also to sort the strings, do as below :

ar = [1, "cool", 3, "story", 4, "bro"]
ar.grep(Fixnum).sort + ar.grep(String).sort
# => [1, 3, 4, "bro", "cool", "story"]
like image 186
Arup Rakshit Avatar answered Dec 30 '25 08:12

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!