Sort array of string with digits and characters in ruby

ruby sort array of strings alphabetically
ruby array sort
ruby sort array numerically
ruby sort array of arrays
ruby sort array of hashes
ruby sort array descending
ruby sort array of objects
ruby sort by date

I have an array with the given strings

array = [
  "1mo-30-super",
  "1mo-40-classic",
  "1mo-30-classic",
  "1mo-110-super",
  "1mo-20-extra",
  "6mo-21-super",
  "6mo-11-super",
  "12mo-21-classic",
  "12mo-21-super"
]

How can I sort the array so that it goes in numerical order, then alphabetical order so the array displays like so:

array = [
  "1mo-20-extra",
  "1mo-30-classic",
  "1mo-30-super",
  "1mo-40-classic",
  "1mo-110-super",
  "6mo-11-super",
  "6mo-21-super",
  "12mo-21-classic",
  "12mo-21-super"
]

You're looking for a "natural" sort where the numeric substrings will be compared as numbers as the non-numeric parts will be compared like strings. Conveniently enough, arrays in Ruby compare element-by-element and your format is fairly regular so you can get away with a #sort_by call and a bit of mangling to convert "12mo-21-classic" to [12, 'mo-', 21, '-classic']. Something like this for example:

# This is a bit complicated so we'll give the logic a name.
natural_parts = ->(s) { s.match(/(\d+)(\D+)(\d+)(\D+)/).to_a.drop(1).map.with_index { |e, i| i.even?? e.to_i : e } }
array.sort_by(&natural_parts)

Ruby Tips: Sort Methods |, You're looking for a "natural" sort where the numeric substrings will be compared as numbers as the non-numeric parts will be compared like strings. In other words, I need to sort the list of strings using the letter suffix as the major sort key, and the integer value of the digit prefix as the minor key. I've tried with sort_by method, but it only allows me to sort the array by the letter (if I split each element first)


array.sort_by { |s| [s.to_i, s[/(?<=-)\d+/].to_i, s.gsub(/\A.+-/,'')] }
  #=> ["1mo-20-extra", "1mo-30-classic", "1mo-30-super", "1mo-40-classic", "1mo-110-super",
  #    "6mo-11-super", "6mo-21-super", "12mo-21-classic", "12mo-21-super"]

When sorting arrays the method Arrays#<=> is used to order pairs of arrays. See the third paragraph of the doc for an explanation of how that is done.

The arrays used for the sort ordering are as follows.

array.each do |s|
  puts "%-15s -> [%2d, %3d, %s]" % [s, s.to_i, s[/(?<=-)\d+/].to_i, s.gsub(/\A.+-/,'')]
end

1mo-30-super    -> [ 1,  30, super]
1mo-40-classic  -> [ 1,  40, classic]
1mo-30-classic  -> [ 1,  30, classic]
1mo-110-super   -> [ 1, 110, super]
1mo-20-extra    -> [ 1,  20, extra]
6mo-21-super    -> [ 6,  21, super]
6mo-11-super    -> [ 6,  11, super]
12mo-21-classic -> [12,  21, classic]
12mo-21-super   -> [12,  21, super]

(?<=-) is a positive lookbehind. It requires that the match be immediately preceded by a hyphen. /\A.+-/ matches the beginning of the string followed by one or more characters followed by a hyphen. Because regular expressions are by default greedy, it concludes the match on the second hyphen.

Note that it is not necessary to use regular expressions:

array.sort_by { |s| [s.to_i, s[s.index('-')+1..-1].to_i, s[s.rindex('-')+1..-1]] }

How to Sort Arrays & Hashes in Ruby (Examples Included), .sort. By default, Ruby's .sort method will sort any array of numbers or When sorting strings, Ruby considers letters that come earlier in the  How to Sort Hashes in Ruby. You are not limited to sorting arrays, you can also sort a hash. Example: hash = {coconut: 200, orange: 50, bacon: 100} hash.sort_by (&:last) # [ [:orange, 50], [:bacon, 100], [:coconut, 200]] hash = {coconut: 200, orange: 50, bacon: 100} hash.sort_by(&:last)


You can chain several #sort method calls, each sorting by a different part of a string (starting with one with smallest priority):

array.sort { |a,b| a.match(/-(.*)$/)[1] <=> b.match(/-(.*)-/)[1] } # sort by last element ('classic', 'super')
     .sort { |a,b| a.match(/-(\d+)-/)[1].to_i <=> b.match(/-(\d+)-/)[1].to_i } # sort by the number between dashes 
     .sort { |a,b| a.to_i <=> b.to_i  } # sort by the initial number

=> ["1mo-20-extra",
 "1mo-30-classic",
 "1mo-30-super",
 "1mo-40-classic",
 "1mo-110-super",
 "6mo-11-super",
 "6mo-21-super",
 "12mo-21-super",
 "12mo-21-classic"]

Ruby Sort Arrays (Use Block Syntax), The Ruby sort method helps you order your data (arrays & hashes) in whatever way Let's say you want to numerically sort a list of strings that contain numbers. Sorting Arrays. Technically, sorting is a job handled by the Enumerable module. The Enumerable module is what ties all types of collections in Ruby together. It handles iterating over collections, sorting, looking through and finding certain elements, etc.


Ruby: Natural sort strings with Umlauts and other funny characters , We handle strings, numbers, and even classes. We sort based on anything. String array. This program creates a string array with 3 characters  All objects in Ruby have a to_s method, which converts the object to a string. This is what the print statement uses. Given our array of sharks: sharks = ["Hammerhead", "Great White", "Tiger", "Whale"] Calling the to_s method creates this string: " [\"Hammerhead\", \"Great White\", \"Tiger\", \"Whale\"]"


Ruby's Sort and Sort_by, Ruby's sort method doesn't work as expected with German umlauts: Also numbers in strings will be sorted character by character which you probably don't​  I needed to sort string alphabetically in ruby. There is a handy chars method on string that converts a string to char array. #Case Sensitive my_string.chars.sort.join # Case Insensitive str.chars.sort{|a,b| a.casecmp(b)}.join # or str.chars.sort_by(&:downcase).join. Related External Links: Stack Overflow - how-to-sort-a-strings-characters


Arrange given numbers to form the biggest number, The Ruby sort method works by comparing elements of a collection through the Put all the numbers smaller than or equal to the pivot to its left. So you can just sort that array, and then join the elements back into a string. interested in learning more about how strings work in Ruby, check out How to Use Strings in Ruby. Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects. Ruby arrays are not as rigid as arrays in other languages. Ruby arrays grow automatically while adding elements to them. Creating Arrays. There are many ways to create or initialize an array. One way is with the new class method − names = Array.new You can set the size of an array at the time of creating array − names = Array.new(20)