简体   繁体   中英

How to sort Ruby array with mixed Strings and Fixnums

I need to sort a mixed array in Ruby. It has Fixnum s and String s

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

I want the Fixnum s 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'

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"]
a, b = [1, "cool", 3, "story", 4, "bro"].partition(&Fixnum.method(:===))
a.sort + b #=> [1, 3, 4, "cool", "story", "bro"]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM