mu_sa
mu_sa

Reputation: 2725

Populating two dimensional array with Hash Keys for similar Values

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

Answers (3)

sawa
sawa

Reputation: 168101

hash.group_by{|k, v| v}.values.map(&:first)

Upvotes: 1

oldergod
oldergod

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.

Hash API.

Upvotes: 3

Dmitri
Dmitri

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

Related Questions