tags:

views:

685

answers:

1

In some scenario of Ruby 1.8. If i have a hash

# k is name, v is order
foo = { "Jim" => 1, "bar" => 1, "joe" => 2}
sortedByValues = foo.sort {|a, b| a[1] <==> b[1]}
#sortedByValues is an array of array not longer a hash!
sortedByValues.keys.join ','

my workaround is to make method to_hash for Array class.

class Array
 def to_hash(&block)
  Hash[*self.collect { |k, v|
   [k, v]
  }.flatten]
 end

end

then, I can do.

ortedByValues.to_hash.keys.join ','

Is there a better way to do this?

+2  A: 

Hashes are unordered by definition. There can be no such thing as a sorted Hash. Your best bet is probably to extract the keys from the sorted array using collect and then do a join on the result

sortedByValues = foo.sort {|a, b| a[1] <==> b[1]}
sortedByValues.collect { |a| a[0] }.join ','
Noel Walters