开发者

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 the开发者_StackOverflow中文版re 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.


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]}


test.values.sort.join(' ')


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(' ')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜