给定以下哈希 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/