从字符串和数组数组创建哈希

时间:2018-09-27 19:56:12

标签: ruby

我有一个像这样的数组:

[
  "temp-1",
  [69.63076923076923, 5.397898451463096],
  "temp-2",
  [70.44, 0.9044335243676014],
  "hum-1",
  [45.199999999999996, 0.09999999999999788],
  "hum-2",
  [43.82, 1.0568822072492268]
]

我想将其转换为哈希,以字符串作为键,并将数组作为值:

{
  "temp-1" => [69.63076923076923, 5.397898451463096],
  "temp-2" => [70.44, 0.9044335243676014],
  ...
}

什么是干净的方法?

1 个答案:

答案 0 :(得分:5)

您可以使用Hash[...],下面是一个示例:

=> array = ["temp-1", [69.63076923076923, 5.397898451463096], "temp-2", [70.44, 
0.9044335243676014], "hum-1", [45.199999999999996, 
0.09999999999999788], "hum-2", [43.82, 1.0568822072492268]]
=> Hash[*array]
#> {"temp-1"=>[69.63076923076923, 5.397898451463096], "temp-2"=>[70.44, 0.9044335243676014], "hum-1"=>[45.199999999999996, 0.09999999999999788], "hum-2"=>[43.82, 1.0568822072492268]}