Ferdy
Ferdy

Reputation: 678

hash using multiple array value in ruby

How I'm trying to build a hash for the following input

[["Company", "Add"], ["Company", "Edit"], ["Company", "Delete"], ["Company", "List"], ["Caterer", "Add"], ["Caterer", "Edit"], ["User", "Add"]] 

The output should be

[{'Company'=>['Add', 'List', 'Edit', 'Delete']},
 {'Caterer'=>['Add', 'List', 'Edit', 'Delete']},
 {'User'=>['Add']}]

Try 1:

input = [["Company", "Add"], ["Company", "Edit"], ["Company", "Delete"], ["Company", "List"], ["Caterer", "Add"], ["Caterer", "Edit"], ["User", "Add"]]
a=[]
input.each do |inp|
  tmp = Hash.new
  a<< tmp.update(inp[0] => inp[1])
end

result:

[{"Company"=>"Add"}, {"Company"=>"Edit"}, {"Company"=>"Delete"}, {"Company"=>"List"}, {"Caterer"=>"Add"}, {"Caterer"=>"Edit"}, {"User"=>"Add"}] 

Upvotes: 1

Views: 64

Answers (2)

Horacio
Horacio

Reputation: 2965

This should work

result={}
[["Company", "Create"], ["Company", "Edit"], ["Company", "Delete"], ["Company", "List"], ["Caterer", "Create"], ["Caterer", "Edit"], ["User", "Add"]].each do  |value|
   result[value[0]]=[] unless result.has_key? value[0]
   result[value[0]] << value[1]
end
puts result.to_s

{"Company"=>["Create", "Edit", "Delete", "List"], "Caterer"=>["Create", "Edit"], "User"=>["Add"]}

But is not an array of hashes

If you still want to get a array you could do this

r=result.map{|k,v| {k=>v} }

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36101

input = [["Company", "Add"], ["Company", "Edit"], ["Company", "Delete"], ["Company", "List"], ["Caterer", "Add"], ["Caterer", "Edit"], ["User", "Add"]]

as_hash = input.group_by(&:first)
as_hash.each do |entity, actions|
  as_hash[entity] = actions.flatten.reject do |action|
    action == entity
  end.sort_by { |action| ['Add', 'List', 'Edit', 'Delete'].index action }
end

EDIT: I just saw that you want an array of the pairs, instead of a hash. You can do that by:

as_hash.map { |pair| Hash[*pair] }

Upvotes: 1

Related Questions