How can I sort the numbers as if they were words?

Ruby will Array#sortby default sort numbers like this in the order of their value:

[11, 12, 13, 112, 113, 124, 125, 127]

I would like to sort an array of numbers like this, as if they were in alphabetical order:

[11, 112, 113, 12, 124, 125, 127, 13]

How can i do this? (Ultimately, I want to do this with Hash keys, so if you want to answer that way, that's fine.) Also, is there a name for this sort type?

+3
source share
3 answers

You are all crqzy))) I have a solution like this:

a.sort_by &:to_s
+7
source

Well, one way is to convert all values ​​to strings, and then convert them.

a = [11, 12, 13, 112, 113, 124, 125, 127]
a = a.map(&:to_s).sort.map(&:to_i)
p a # => [11, 112, 113, 12, 124, 125, 127, 13]
+2
source

, . , - , .

a = [11, 112, 113, 12, 124, 125, 127, 13]
new_a = a.sort do |x,y|
  "%{x}" <=> "%{y}"
end
puts new_a

Note. I suspect that the reason you are looking for such a solution is because the objects you want to sort are not Integerat heart. This may be appropriate and semantically more pleasant for a subclass Integer. Although this will obviously make creating an instance more complicated, it seems more correct, at least for me.

+1
source

Source: https://habr.com/ru/post/1786929/