How do I sort an array of mixed strings and numbers in Ruby?

Question: Question:

I have an array with a mixture of strings and numbers as elements. I want to sort all of this in numerical order, what should I do?

For example, if you have the following array:

["123", 200, "12", 85]

I want to sort this as follows.

["12", 85, "123", 200]

Answer: Answer:

You can sort by using the sort_by method.

["123", 200, "12", 85].sort_by{|item| item.to_i} #=> ["12", 85, "123", 200]

It is the same even if you write as follows.

["123", 200, "12", 85].sort_by(&:to_i) #=> ["12", 85, "123", 200]
Scroll to Top
AllEscort