Sorting a list by two criteria in Ruby

This is more a Ruby question than an SketchUp API question but I thought I might ask it here since there are some very powerful Ruby coders who frequent this board, much more so than myself.

I have a list like the following:

list1 = [W20, W1, W8, K2, K4, W2, K1]

I would like to sort this list so that I get the following result:

list1 = [K1, K2, K4, W1, W2, W8, W20]

I’ve tried this code:

list1.sort_by! { |e| e[/\d+/].to_i }

but it intermingles the K and W items in the list, is there an easy way to alphabetically sort and numerically sort the list. Maybe this is a multi-step process, it is probably simple but I’m not seeing it.

I tried this but it doesn’t seem to work:

list1.sort_by! { |e| 

if I understand your question

Divide the String into characters and numbers, then sort_by with the the array [ String, Interger]

list1 = ['W20', 'W1', 'W8', 'K2', 'K4', 'W2', 'K1']
res = list1.sort_by { |e| [ e[/\D+/], e[/\d+/].to_i] }
p res

That works.

I was on the right path with the two part sorting but I just didn’t quite have it right.

Thank-you for squaring me away.

1 Like

So I know there a solution but I try to ask Chat GPT and here’s the answer:

list1 = ["W20", "W1", "W8", "K2", "K4", "W2", "K1"]

# Sort by the alphabetic part first, and then by the numeric part
list1.sort_by! do |e|
  letter = e[/[A-Za-z]+/]  # Extracts the alphabetic part
  number = e[/\d+/].to_i   # Extracts the numeric part and converts it to an integer
  [letter, number]         # Array used for comparison; Ruby sorts by each element in order

puts list1.inspect

1 Like