0

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?

1
  • 1
    Your question is a bit unclear. What is the exact output you're looking for? Commented Mar 7, 2013 at 1:59

6 Answers 6

1

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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]]]

1 Comment

This is how I understood his question too
0

Try this:

hash.map { |k,v| { k => v} }

It returns:

{"a"=>[1, 2, 3]}
{"b"=>[18, 21, 9]}

Comments

0

is this what you want?

hash.map{|key,value| [key]+value }
=> [["a", 1, 2, 3], ["b", 18, 21, 9]]

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.