I have an array ["Q10", "Q100", "Q1000", "Q1000a", "Q1001", "Q98"]
. After sorting it, I get the following result:
['Q100', 'Q1000', 'Q1000a','Q98', 'Q10', 'Q1001'].sort
["Q10", "Q100", "Q1000", "Q1000a", "Q1001", "Q98"]
Because of this behaviour, I cannot sort my ActiveRecord objects correctly. I have a model of Question
which has a field label
. I need to sort it based on label. So Question with label Q1
would be first and the question with label Q1a
would follow and so on. I get in a similar order with ActiveRecord described to the above example of array. I am using postgresql as my database.
Now I have 3 questions.
- Why alphanumeric string sorting behave that way?
- How can I achieve my required sorting without using the sort block?
- How can I achieve that sorting in ActiveRecord?
If your array were
you could write
If
then
See Enumerable#sort_by and String#[].
The regular expression
/\d+/
matches a substring ofs
that contains one or more digits.If the array were
you could write
If
then
The regular expression
/\D+\z/
matches a substring ofs
that contains one or more non-digits at the end (\z
) of the string.See Array#<=>, specifically the third paragraph, for an explanation of how arrays are ordered when sorting.
If the array were
you could write
If
then
The regular expression
/\A\D+/
matches a substring ofs
that contains one or more non-digits at the beginning (\A
) of the string.