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