[英]Ruby hash of arrays
So I have a hash like this: 所以我有一个像这样的哈希:
hash = { "a"=>[1, 2, 3], "b"=>[18, 21, 9] }
I would like to get the whole array, not just the values. 我想获取整个数组,而不仅仅是值。
It seems like this should work: 看来这应该工作:
hash.each{|key,value| value}
[1, 2, 3]
[18, 21, 9]
But what I get is the individual elements of the array-1, 2, 3. I know I can do hash.values, but that gives an array of arrays with no keys. 但是我得到的是array-1、2、3的各个元素。我知道我可以进行hash.values运算,但这给出了没有键的数组数组。 I need the key/value(array) pair. 我需要键/值(数组)对。 Thoughts? 有什么想法吗?
What you are describing does work as intended: 您所描述的确实按预期工作:
=> {"a"=>[1, 2, 3], "b"=>[18, 21, 9]}
[4] pry(main)> hash.each { |k,v| puts v.length }
3
3
Can you post a snippet of code illustrating your specific problem? 您可以张贴一段代码说明您的特定问题吗?
Your construction does give you the whole array: 您的构造确实会为您提供整个阵列:
irb(main):001:0> hash = { "a" => [1, 2, 3], "b" => [18, 21, 9] }
=> {"a"=>[1, 2, 3], "b"=>[18, 21, 9]}
irb(main):002:0> hash.each{ |key,value| puts value.class.name }
Array
Array
Perhaps you are just trying to puts
an array? 也许您只是想puts
一个数组? If so, by default that puts each element on a separate line. 如果是这样,则默认情况下会将每个元素放在单独的行上。
irb(main):003:0> puts [1,2,3]
1
2
3
Not sure if I fully understood but are you asking for something like this (using .to_a
): 不知道我是否完全理解,但是您是否要求这样(使用.to_a
):
hash = { "a"=>[1, 2, 3], "b"=>[18, 21, 9] }
=> {"a"=>[1, 2, 3], "b"=>[18, 21, 9]}
arr = hash.to_a
=> [["a", [1, 2, 3]], ["b", [18, 21, 9]]]
Try this: 尝试这个:
hash.map { |k,v| { k => v} }
It returns: 它返回:
{"a"=>[1, 2, 3]}
{"b"=>[18, 21, 9]}
is this what you want? 这是你想要的吗?
hash.map{|key,value| [key]+value }
=> [["a", 1, 2, 3], ["b", 18, 21, 9]]
If you have this 如果你有这个
hash = { "a"=>[1, 2, 3], "b"=>[18, 21, 9] }
and you want the whole array to be returned just use the key accessor. 并且您只需要使用键访问器就可以返回整个数组。 For example 例如
hash[:a] = [1, 2, 3]
hash[:b] = [18, 21, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.