Parametric sort

Hi!

I want to sort a number of File::Stat object due to the user’s choice.
[Anyway, can I read back the filename from the Stat object?]

My idea was to build a hash, keys are ‘name’, ‘size’, … and values are
proc objects doing the comparism. Then I just can write.

userChoice=‘size’
myArray.sort(sortMethods[userChoice])

But I don’t know the correct syntax.
I’m still using ruby1.6, if it matters.

±[Kontra, Gergely @ Budapest University of Technology and Economics]-+

    Email: kgergely@mcl.hu,  kgergely@turul.eet.bme.hu          |

URL: turul.eet.bme.hu/~kgergely Mobile: (+36 20) 356 9656 |
±------“Olyan langesz vagyok, hogy poroltoval kellene jarnom!”-------+
.
Magyar php mirror es magyar php dokumentacio: http://hu.php.net

userChoice='size'
myArray.sort(sortMethods[userChoice])

Something like this ?

pigeon% cat b.rb
#!/usr/bin/ruby
SM = {
   'name' => proc {|a, b| a <=> b},
   'size' => proc {|a, b| b <=> a}
}
p [1, 3, 2].sort &SM['name']
p [1, 3, 2].sort &SM['size']
pigeon%

pigeon% b.rb
[1, 2, 3]
[3, 2, 1]
pigeon%

Guy Decoux

Hi!

I want to sort a number of File::Stat object due to the user’s choice.
[Anyway, can I read back the filename from the Stat object?]

No you cant.

My idea was to build a hash, keys are ‘name’, ‘size’, … and values are
proc objects doing the comparism. Then I just can write.

userChoice=‘size’
myArray.sort(sortMethods[userChoice])

But I don’t know the correct syntax.
I’m still using ruby1.6, if it matters.

Try this.

class Array
def sort_by(method)
self.sort { |a,b| a.send(method) <=> b.send(method) }
end
end

user_choice = ‘size’
array.sort_by(user_choice)

I believe sort_by is introduced in 1.7.

±[Kontra, Gergely @ Budapest University of Technology and Economics]-+

Gavin

···

----- Original Message -----
From: “Kontra, Gergely” kgergely@mlabdial.hit.bme.hu