rmontgomery429
rmontgomery429

Reputation: 14860

How can I sort this hash given these keys in ruby?

So I've got this Hash. It looks like this:

{
  'arg0' => '126150656000',
  'arg1' => 'Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz',
  'arg2' => '2790',
  'arg3' => '3276320768',
  'arg4' => '8467496960',
  'arg5' => 'Windows 7',
  'arg6' => '6.1',
  'arg7' => 'amd64',
  'arg8' => '2',
  'arg9' => '1920',
  'arg10' => '1200',
  'arg11' => '32',
}

The Hash needs to be transformed into an array of positional args based on the 'argN' position of the key. Like so.

[
  '126150656000',
  'Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz',
  '2790',
  '3276320768',
  '8467496960',
  'Windows 7',
  '6.1',
  'amd64',
  '2',
  '1920',
  '1200',
  '32'
]

The goal here is that [0] == ['arg0'], [1] == ['arg1'], [N] == ['argN'].

NOTE:

The keys can NOT be guaranteed to be in the correct order. For example the hash above may have 'arg9' "before" 'arg4'. Sorry for not making that clear.

Upvotes: 2

Views: 103

Answers (3)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34071

Disorganizing your Hash first:

h = {
  'arg1' => 'Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz',
  'arg3' => '3276320768',
  'arg4' => '8467496960',
  'arg7' => 'amd64',
  'arg5' => 'Windows 7',
  'arg2' => '2790',
  'arg6' => '6.1',
  'arg9' => '1920',
  'arg8' => '2',
  'arg0' => '126150656000',
  'arg10' => '1200',
  'arg11' => '32',
}

You can do this:

h.keys.sort.map{|k| h[k]}
# => ["126150656000", "Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz", "1200",
#     "32", "2790", "3276320768", "8467496960", "Windows 7", "6.1",
#     "amd64", "2", "1920"]

Update: This is assuming that you want your keys sorted in standard sort order, which if they are literally 'arg0' through 'arg11', isn't what you expect. I'm guessing your actually keys are something more useful. If these are you actual keys, you might do:

h.keys.sort_by{|s| s[3..-1].to_i}.map{|k| h[k]}
# => ["126150656000", "Intel(R) Core(TM) i7-2640M CPU @ 2.80GHz", "2790",
#     "3276320768", "8467496960", "Windows 7", "6.1", "amd64", "2", "1920",
#     "1200", "32"]

Upvotes: 1

undur_gongor
undur_gongor

Reputation: 15954

 h.sort_by { | a, _ | a.gsub(/[^\d]/, '').to_i }.map(&:last)

Upvotes: 5

Viet
Viet

Reputation: 3397

The answers provided are good if the hash contains keys that are unsorted. Based on your example, it looks like they are already ordered. If thats the case, then all you need to do is do {}.values to obtain the "ordered" array of the values.

Upvotes: 0

Related Questions