3

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'

3 Answers 3

6

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"]
Sign up to request clarification or add additional context in comments.

Comments

1
a, b = [1, "cool", 3, "story", 4, "bro"].partition(&Fixnum.method(:===))
a.sort + b #=> [1, 3, 4, "cool", "story", "bro"]

Comments

1

Practically, I have always needed to sort by Fixnum first and followed by String elements:

ar.sort_by { |n| n.to_s } # => [1, 3, 4, "bro", "cool", "story"]

This only converts an element into string within the block for comparison but returns the Fixnum in it's original state

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.