arrays - 从以数组为值的散列中获取数组

标签 arrays ruby hash enumerable

给定以下哈希 hash,键为符号,值为数组:

hash
#=> {:stage_item=>[:stage_batch_id, :potential_item_id], :item=>[:id, :size, :color, :status, :price_sold, :sold_at], :style=>[:wholesale_price, :retail_price, :type, :name]}

如何获得仅将值(数组)加在一起的数组?

我知道我可以使用 #each_with_object#flatten :

hash.each_with_object([]) { |(k, v), array| array << v }.flatten
#=> [:stage_batch_id, :potential_item_id, :id, :size, :color, :status, :price_sold, :sold_at, :wholesale_price, :retail_price, :type, :name]

但我只希望 #each_with_object 能工作:

hash.each_with_object([]) { |(k, v), array| array += v }
#=> []

虽然每个 with 对象的要点是它跟踪累加器(在本例中名为 array),所以我可以像下面那样 +=示例:

arr = [1,2,3]
#=> [1, 2, 3]
arr += [4]
#=> [1, 2, 3, 4]

我错过了什么?

最佳答案

Array << ..就地更改原始数组:

irb(main):014:0> a = original = []
=> []
irb(main):015:0> a << [1]
=> [[1]]
irb(main):016:0> a
=> [[1]]
irb(main):017:0> original
=> [[1]]
irb(main):018:0> a.equal? original  # identity check
=> true

同时,Array += ..返回一个新数组而不改变原始数组:

irb(main):019:0 a = original = []
=> []
irb(main):020:0> a += [1]
=> [1]
irb(main):021:0> a
=> [1]
irb(main):022:0> original
=> []
irb(main):023:0> a.equal? original
=> false

根据 Enumerable#each_with_object documentation ,

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

If no block is given, returns an enumerator.

因此,在 += 的情况下, 返回未修改的初始空数组。


顺便说一句,而不是使用 each_with_object , 你可以简单地使用 Hash#values method它返回一个新数组,其中填充了散列中的值:

hash.values.flatten

关于arrays - 从以数组为值的散列中获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42262652/

相关文章:

JavaScript 数组表现得像一个对象

arrays - 如何将两个 Unicode 字符合并为一个

java - 从 txt 文件中读取整数并存储到数组中

ruby-on-rails - 我怎样才能从 gem 的类(class)中消除我自己的类(class)的歧义

ruby - 如何在 Ruby 中将十六进制转换为二进制(反之亦然),同时保持前导零?

ruby - Paypal REST API - 缺少描述/项目名称

algorithm - 用于无序 ID 集的良好哈希函数

c# - 是否存在一种 C# 哈希生成方法,其中值的顺序无关紧要?

ruby - 在 Ruby 中交换散列键和局部变量名

java - 对象数组的 getter 和 setter?