我有哈希,它的所有值都是数组,如下所示:
list = { letter: ['a', 'b', 'c'],
number: ['one', 'two', 'three'],
fruit: ['apple', 'pear', 'kiwi'],
car: ['vw', 'mb', 'bmw'],
state: ['la', 'ny', 'fl'],
color: ['red', 'white', 'black'],
tree: ['oak', 'pine', 'maple'],
animal: ['cat', 'dog', 'rat'],
clothes: ['tie', 'sock', 'glove'] }
事实上,这个哈希可能有更多的键,值可能更大,但每个值的大小总是相同的(在这种情况下 - 三个).
我想将此哈希转换为哈希数组.
每个哈希都将具有所有原始哈希密钥和相应的值.
最后我想要:
list = [
{ letter: 'a', number: 'one', fruit: 'apple', car: 'vw', state: 'la',
color: 'red', tree: 'oak', animal: 'cat', clothes: 'tie' },
{ letter: 'b', number: 'two', fruit: 'pear', car: 'mb', state: 'ny',
color: 'white', tree: 'pine', animal: 'dog', clothes: 'sock' },
{ letter: 'c', number: 'three', fruit: 'kiwi', car: 'bmw', state: 'fl',
color: 'black', tree: 'elm', animal: 'rat', clothes: 'glove' }
]
最好的方法是什么?
1> Cary Swovela..:
[list.keys].product(list.values.transpose).map { |a| a.transpose.to_h }
#=> [{:letter=>"a", :number=>"one", :fruit=>"apple", :car=>"vw",
# :state=>"la", :color=>"red", :tree=>"oak", :animal=>"cat",
# :clothes=>"tie"},
# {:letter=>"b", :number=>"two", :fruit=>"pear", :car=>"mb",
# :state=>"ny", :color=>"white", :tree=>"pine", :animal=>"dog",
# :clothes=>"sock"},
# {:letter=>"c", :number=>"three", :fruit=>"kiwi", :car=>"bmw",
# :state=>"fl", :color=>"black", :tree=>"maple", :animal=>"rat",
# :clothes=>"glove"}]
假设list
定义如下.
list = {
letter: ['a', 'b' ],
number: ['one', 'two' ],
fruit: ['apple', 'pear'],
car: ['vw', 'mb' ]
}
步骤如下.
b = [list.keys]
#=> [[:letter, :number, :fruit, :car]]
c = list.values
#=> [["a", "b"], ["one", "two"], ["apple", "pear"], ["vw", "mb"]]
d = c.transpose
#=> [["a", "one", "apple", "vw"],
# ["b", "two", "pear", "mb"]]
e = b.product(d)
#=> [[[:letter, :number, :fruit, :car], ["a", "one", "apple", "vw"]],
# [[:letter, :number, :fruit, :car], ["b", "two", "pear", "mb"]]]
e.map { |a| a.transpose.to_h }
#=> [{:letter=>"a", :number=>"one", :fruit=>"apple", :car=>"vw"},
# {:letter=>"b", :number=>"two", :fruit=>"pear", :car=>"mb"}]
让我们更仔细地看看最后一步.map
将第一个元素传递e
给块并将块变量a
设置为其值:
a = e.first
#=> [[:letter, :number, :fruit, :car],
# ["a", "one", "apple", "vw"]]
块计算如下.
f = a.transpose
#=> [[:letter, "a"], [:number, "one"], [:fruit, "apple"], [:car, "vw"]]
f.to_h
#=> {:letter=>"a", :number=>"one", :fruit=>"apple", :car=>"vw"}
其余的计算e.map { |a| a.transpose.to_h }
是类似的.