Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
Re: Sorting a Hash
Rick DeNatale
3/1/2007 3:43:00 PM
On 2/28/07, Nasir Khan <rubylearner@gmail.com> wrote:
> I want to order such that the keys (or values) when returned in an array are
> ordered.
> Obviously the above snipper does *not* work because Hash#sort does not sort
> the Hash but returns an array of arrays with elements sorted according to
> sort block.
>
> I can maintain a parallel array of sorted keys but it is kind of kludgy.
> Can I sort the hash "in place" such that the Hash#keys and Hash#values
> return sorted results, without me having to maintain this array of arrays
> separately?
Well there's nothing stopping you from adding methods to Hash to
return sorted keys and values. Of course you can also just do
hash.keys.sort
or
hash.values.sort
The first one will likely do what you want, but I suspect that what
you really want for values is to get them as ordered by the sorted
keys.
Here's a quick implementation of two additional methods for hash, I
wouldn't recommend changing the implementation of the existing keys
and values methods:
rick@frodo:/public/rubyscripts$ cat shash.rb
class Hash
def sorted_keys(&sort_block)
keys.sort(&sort_block)
end
def values_sorted_by_keys(&sort_block)
values_at(*sorted_keys(&sort_block))
end
end
test_hash = {"Fred" => "Wilma", "Barney" => "Betty",
"Ricky" => "Lucy", "Fred" => "Ethel",
"Ralph" => "Alice", "Ed" => "Trixie"}
p test_hash.keys
p test_hash.values
p test_hash.sorted_keys
p test_hash.values_sorted_by_keys
p test_hash.sorted_keys {|a, b| b <=> a}
p test_hash.values_sorted_by_keys {|a, b| b <=> a}
rick@frodo:/public/rubyscripts$ ruby shash.rb
["Ralph", "Ricky", "Barney", "Fred", "Ed"]
["Alice", "Lucy", "Betty", "Ethel", "Trixie"]
["Barney", "Ed", "Fred", "Ralph", "Ricky"]
["Betty", "Trixie", "Ethel", "Alice", "Lucy"]
["Ricky", "Ralph", "Fred", "Ed", "Barney"]
["Lucy", "Alice", "Ethel", "Trixie", "Betty"]
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denh...
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
Re: Sorting a Hash
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password