如何在一行中遍历此哈希? [英] How to traverse this hash within one line?
问题描述
哈希中的每个键都有一个也是哈希的值.
Each key in a hash has a value that's also a hash.
{
100 => {
1 => 'ruby',
2 => 'enumerables'
},
50 => {
3 => 'can',
4 => 'cause'
},
15 => {
5 => 'occassional',
6 => 'insanity'
}
}
对于每个哈希对象,我想舍弃顶级键,然后将其替换为嵌套哈希对象的键和值.
For each hash object, I want to discard the top-level key, and replace it with the key and value of the nested hash objects.
{
1 => 'ruby',
2 => 'enumerables',
3 => 'can',
4 => 'cause',
5 => 'occasional',
6 => 'insanity'
}
我可以使用它,但是我的方法使用merge!
,并且需要创建另一个散列来存储值.我很好奇,看看是否可以在一行中完成.我尝试使用reduce()
,但无法使其正常工作.
I have it working, but my method uses a merge!
, and requires creating another hash to store the values. I'm curious to see if it can be done in one line. I tried to use reduce()
, but could not make it work.
推荐答案
这有效:
hash.values.inject(&:merge)
另一种选择,使用reduce
(与inject
相同),并注意tokland的注释,即在使用符号时会自动调用to_proc:
Another option, using reduce
(which is the same as inject
), and noting tokland's comment that to_proc is automatically called when you use a symbol:
hash.values.reduce(:merge)
然后它不仅变得简洁,而且可读性强.
Then it becomes not only concise but very readable.
这篇关于如何在一行中遍历此哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!