我是如何尝试为以下输入构建哈希
[["Company", "Add"], ["Company", "Edit"], ["Company", "Delete"], ["Company", "List"], ["Caterer", "Add"], ["Caterer", "Edit"], ["User", "Add"]]
输出应为
[{'Company'=>['Add', 'List', 'Edit', 'Delete']},
{'Caterer'=>['Add', 'List', 'Edit', 'Delete']},
{'User'=>['Add']}]
尝试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
结果:
[{"Company"=>"Add"}, {"Company"=>"Edit"}, {"Company"=>"Delete"}, {"Company"=>"List"}, {"Caterer"=>"Add"}, {"Caterer"=>"Edit"}, {"User"=>"Add"}]
答案 0 :(得分:1)
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
编辑:我刚看到你想要一对数组,而不是哈希。你可以通过以下方式做到:
as_hash.map { |pair| Hash[*pair] }
答案 1 :(得分:0)
这应该有效
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"]}
但不是哈希数组
如果您仍想获得阵列,可以执行此操作
r=result.map{|k,v| {k=>v} }