Reputation: 2725
I am new to Ruby. I have a (already sorted) hash with the following values. I want to put the keys of these in multidimensional array on the basis of there values. So, for example
For
VALUES - KEYS
acemrs - a
acemrs - b
acrs - c
acrs - d
acrs - e
aeoopstt - f
for - g
foru -h
I am looking for an array like [ [a,b] , [c,d,e] , [f] , [g] , [h] ]
Upvotes: 2
Views: 1307
Reputation: 15010
hash = {'a'=>'acemrs','b'=>'acemrs','c'=>'acrs','d'=>'acrs','e'=>'acrs','f'=>'aeoopstt','g'=>'for','h'=>'foru'}
new_hash = {}
hash.each_pair do |key, value|
(new_hash[value] ||= []) << key
end
array = new_hash.values
We use the previous hash values
as keys
for the new hash. If undefined, we create a new array for each new keys
with new_hash[value] ||= []
then just push all keys in the new hash with << key
. The new hash will be something like
{"aeoopstt"=>["f"], "for"=>["g"], "acemrs"=>["b", "a"], "acrs"=>["e", "d", "c"], "foru"=>["h"]}
At the end, you just want those values so new_hash.values
and you are done.
Upvotes: 3
Reputation: 2748
Just working off this question: Ruby multidimensional array
You can use NArray, a Ruby numerical array library:
require 'narray'
array = NArray[ [a,b] , [c,d,e] , [f] , [g] , [h] ]
then
array[1][2]
would return 'b', and array[2][3]
would return 'e', et c.
Upvotes: 0