简体   繁体   English

如何将嵌套的哈希值收集到ruby中的数组中?

[英]How do I collect nested hash values into an array in ruby?

Say I have the following hash. 说我有以下哈希值。

my_hash = {
  'array1' => %w[
    value1
    value2
  ],
  'array2' => %w[
    value3
    value4
  ]
}

How do I make an array that looks like 我如何制作一个看起来像的数组

my_array = %w[value1 value2 value3 valuu4]
my_array = my_hash.values.flatten
=> ["value1", "value2", "value3", "value4"]

Flatten Hash Values 扁平化哈希值

Use Hash#values to collect the values from your Hash, and then use Array#flatten to turn the result into a single Array rather than one containing nested arrays. 使用Hash#values从您的Hash中收集值,然后使用Array#flatten将结果转换为单个Array,而不是一个包含嵌套数组的数组。 For example: 例如:

my_hash.values.flatten
#=> ["value1", "value2", "value3", "value4"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM