【发布时间】:2017-07-04 21:32:13
【问题描述】:
给定以下哈希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]
我错过了什么?
【问题讨论】:
标签: arrays ruby hash enumerable