数组中的哈希

时间:2016-02-29 15:32:39

标签: arrays ruby hash

我有这个哈希:

{"id" => [323, 324], info => ["Test Info", "Test Info2"]}

我想在这样的数组中有一个哈希:

array = [
  [{"id" => "323", info => "Test Info"}],
  [{"id" => "324", info => "Test Info2"}]
]

我有重复的数据。我需要在uniqid上使用info来获取每个id一次。因此,我需要在之后加入他们。

5 个答案:

答案 0 :(得分:2)

h = {"id" => [323, 324], "info" => ["Test Info", "Test Info2"]}

h.map { |k, v| [k].product v }.transpose.map &:to_h

#⇒ [
#  [0] {
#      "id" => 323,
#    "info" => "Test Info"
#  },
#  [1] {
#      "id" => 324,
#    "info" => "Test Info2"
#  }
]

如果要将每个嵌套的哈希包装到它自己的数组中,还需要执行一个操作:

h.map { |k, v| [k].product v }.transpose.map(&:to_h).map { |e| [e] }

#⇒ [
#  [0] [
#    [0] {
#        "id" => 323,
#      "info" => "Test Info"
#    }
#  ],
#  [1] [
#    [0] {
#        "id" => 324,
#      "info" => "Test Info2"
#    }
#  ]
# ]

答案 1 :(得分:1)

您可以使用此解决方案(在这种情况下可能是OP)

h = {"id" => [323, 324], "info" => ["Test Info", "Test Info2"]}

h.values.transpose.map do |a|
  [Hash[h.keys.each_with_index.map { |k, i| [k, a[i]] }]]
end

# => [[{"id"=>323, "info"=>"Test Info"}], [{"id"=>324, "info"=>"Test Info2"}]]

答案 2 :(得分:1)

这看起来像zip的工作,它将两个数组拉链在一起:

hash = {
  "id" => [323, 324],
  "info" => ["Test Info", "Test Info2"]
}

keys = %w[ id info ]

array = hash['id'].zip(hash['info']).map do |id, info|
  Hash[keys.zip(pair)]
end

# => [{"id"=>323, "info"=>"Test Info"}, {"id"=>324, "info"=>"Test Info2"}]

Hash[]方法用于将表单[['a',1],['b',2]]的数组转换为表单{'a'=>1,'b'=>2}的哈希值。

答案 3 :(得分:0)

以下是其他几个:

h = {"id" => [323, 324], "info" => ["Test Info", "Test Info2"]}

da_keys = h.keys
h.values.transpose.each_with_object([]) { |a,b| b << da_keys.zip(a).to_h }
  #=> [{"id"=>323, "info"=>"Test Info"}, {"id"=>324, "info"=>"Test Info2"}] 

rolling_keys = h.keys.cycle
h.values.transpose.map {|a| a.each_with_object({}) {|v,g| g.update(rolling_keys.next=>v)}}
  #=> [{"id"=>323, "info"=>"Test Info"}, {"id"=>324, "info"=>"Test Info2"}] 

答案 4 :(得分:0)

你问了这个:

if (entity.Name.Contains("Auth+"))
{
   modelBuilder.Entity(entity.Name).ToTable(entity.Name.Replace("myproject.Models.Auth+", string.Empty),"auth");
}

但我认为你真正想要的只是这个:

array = [
  [{"id" => "323", info => "Test Info"}],
  [{"id" => "324", info => "Test Info2"}]
]

鉴于此:

array = [
  {"id" => "323", "info" => "Test Info"},
  {"id" => "324", "info" => "Test Info2"}
]

你可以这样做:

h = {"id" => [323, 324], "info" => ["Test Info", "Test Info2"]}