Given the following array:
y = %w[A1 A2 B5 B12 A6 A8 B10 B3 B4 B8]
=> [\"A1\", \"A2\", \"B5\", \"B12\", \"A6\", \"A8\", \"B10\", \"B3\", \"B4\", \"B8\"]
If you know what the maximum amount of digits in your numbers is you can also prefix your numbers with 0
during comparison.
y.sort_by { |string| string.gsub(/\d+/) { |digits| format('%02d', digits.to_i) } }
#=> ["A1", "A2", "A6", "A8", "B3", "B4", "B5", "B8", "B10", "B12"]
Here '%02d'
specifies the following, the %
denotes the formatting of a value, the 0
then specifies to prefix the number with 0
s, the 2
specifies the total length of the number, the d
specifies that you want the output in decimals (base 10). You can find additional info here.
This means that 'A1'
will be converted to 'A01'
, 'B8'
will become 'B08'
and 'B12'
will stay 'B12'
, since it already has 2 digits. This is only used during comparison.