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.
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
end
puts list1.inspect