they changed my name
they changed my name

Reputation: 491

Best way to get the values of a hash ordered by their respective keys? (Ruby)

Here's what I'm doing atm:

test = {
  'd' => 20,
  'b' => 40,
  'c' => 30,
  'a' => 50,
  'e' => 10
}

f = []
test.to_a.sort.each do |e|
  f << e[1]
end
puts f.join(' ')

Outputs:

50 40 30 20 10

Is there a more efficient/concise/better way to do this? And before someone says so, no, I can't use an array. :p

EDIT Sorry, posted the wrong code.

Upvotes: 1

Views: 182

Answers (3)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

test.sort_by(&:first).map(&:last).join(' ')

Unfortunately, Ruby doesn't have a class for representing Hash entries (key-value pairs), but just uses a two-element array instead. If Ruby did have a dedicated class for key-value pairs, this would be much less opaque:

test.sort_by(&:key).map(&:value).join(' ')

And, of course, the fact that Enumerable#sort_by returns an Array, is also quite unfortunate. If it returned a SortedMap or something like that, it would be even nicer:

test.sort_by(&:key).values.join(' ')

Upvotes: 0

Mirko Froehlich
Mirko Froehlich

Reputation: 12046

In your title you mention that you want to get the values of the array sorted by their respective keys. But in your example, you actually just sort the values, regardless of the keys.

If that's what you want, simply use:

test.values.sort

But if you want to sort the values based on the keys, use this:

test.keys.sort.collect {|k| test[k]}

Upvotes: 4

Chandra Patni
Chandra Patni

Reputation: 17577

test.values.sort.join(' ')

Upvotes: 2

Related Questions