将数组变成哈希

时间:2019-09-26 10:56:34

标签: arrays ruby

我有一个红宝石哈希表:

my_array = [{"apples" => 5}, {"oranges" => 12}]

我想将其转换为哈希,哈希键等于数组索引值+1,如下所示:

my_hash = {"1"=>{"apples"=> 5}, "2"=>{"oranges" => 12}}

有什么想法吗?

3 个答案:

答案 0 :(得分:5)

您还可以Enumerable#zip设置范围,然后转换Array#to_h

(1..my_array.size).zip(my_array).to_h
#=> {1=>{"apples"=>5}, 2=>{"oranges"=>12}}

工作原理

my_array.size #=> 2将数组的大小作为整数返回。

(1..my_array.size)是一个包容性的Range,它列举了{strong> integers 表1到数组大小,在这种情况下为2

范围响应Enumerable#zip,因此,例如,您可以执行以下操作获得对数组:

(1..3).zip(:a..:c) #=> [[1, :a], [2, :b], [3, :c]]

最后,可以将成对的数组转换为哈希,请参见Array#to_h

[[1, :a], [2, :b], [3, :c]].to_h #=> {1=>:a, 2=>:b, 3=>:c}

由于范围是整数,因此哈希的键是整数。但是您可以调整代码行以获取字符串作为键。

答案 1 :(得分:3)

-- LLD version: 10.0.0
CMake Error at /usr/share/cmake-3.10/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Could NOT find LibEdit (missing: libedit_INCLUDE_DIRS libedit_LIBRARIES)
Call Stack (most recent call first):
  /usr/share/cmake-3.10/Modules/FindPackageHandleStandardArgs.cmake:378 (_FPHSA_FAILURE_MESSAGE)
  /home/enrique/Escritorio/llvm-project/lldb/cmake/modules/FindLibEdit.cmake:54 (find_package_handle_standard_args)
  /home/enrique/Escritorio/llvm-project/lldb/cmake/modules/LLDBConfig.cmake:104 (find_package)
  /home/enrique/Escritorio/llvm-project/lldb/CMakeLists.txt:21 (include)


-- Configuring incomplete, errors occurred!
See also "/home/enrique/Escritorio/llvm-project/build/CMakeFiles/CMakeOutput.log".
See also "/home/enrique/Escritorio/llvm-project/build/CMakeFiles/CMakeError.log".

答案 2 :(得分:3)

您可以尝试使用Enumerator#with_index获取索引,并使用Enumerator#each_with_object创建新的哈希值

my_array = [{"apples"=> 5}, {"oranges" => 12}]
my_hash = my_array.each.with_index.with_object({}){|(hsh, i), e| e[(i+1).to_s] = hsh}
# => {"1"=>{"apples"=> 5}, "2"=>{"oranges" => 12}}