Luca G. Soave
Luca G. Soave

Reputation: 12689

Can you optimize this descending sorting array with Ruby?

Do you know a better, faster, smarter, efficent or just more elegat way of doing the following ?

due this array

a = [171, 209, 3808, "723", "288", "6", "5", 27, "22", 207, 473, "256", 67, 1536] 

get this

a.map{|i|i.to_i}.sort{|a,b|b<=>a}
 => [3808, 1536, 723, 473, 288, 256, 209, 207, 171, 67, 27, 22, 6, 5]

Upvotes: 1

Views: 122

Answers (2)

edgerunner
edgerunner

Reputation: 14973

Here's one using symbol#to_proc

a.map(&:to_i).sort.reverse

This is faster than using in-place modifier (!) methods but uses more memory. As a bonus, it keeps the original array a intact if you want to do anything else with it.

Upvotes: 2

Chris Heald
Chris Heald

Reputation: 62668

You can use in-place mutations to avoid creating new arrays:

a.map!(&:to_i).sort!.reverse!

Hard to know if it's faster or more efficient without a benchmark, though.

Upvotes: 2

Related Questions