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. 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? 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
):
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.