I have an array of arrays
arr = [
['category','subcat','detail'],['category1','subcat1','detail1']
]
I want to make a hash from it {'category'=>'category','subcat'=>'subcat','detail'=>'detail'}...,other hashes from array
hash={}
what i’m doing it’s
arr.each{|el|
hash['category'] = el[0];
hash['subcat'] = el[1];
hash['detail'] = h[2];
}
but it returns only last element
hash=>{category:'category1',subcat:'subcat1',detail:'detail1'}
when i do it with existing hash keys it works perfectly,but when i try to set new key -doesn’t work
How to fix it?
7
2 Answers
Hashes can only have unique keys, duplicates aren’t allowed. When you insert a duplicate you overwrite any previously existing key with the same name:
Meditate on this:
foo = {} # => {}
foo['a'] = 1
foo # => {"a"=>1}
foo
now is a hash of a single key/value pair. If I try to add another element with the same key I only overwrite the previous value, I don’t add another key/value pair:
foo['a'] = 2
foo # => {"a"=>2}
This is essentially what you’re doing with:
arr.each{|el|
hash['category'] = el[0];
hash['subcat'] = el[1];
hash['detail'] = h[2];
}
To make your code work you’ll need to find different names for the keys for each iteration through the loop.
I can add a different key/value though:
foo['b'] = 3
foo # => {"a"=>2, "b"=>3}
See the documentation or any Ruby hash tutorial for more information.
You can use Array#transpose in combination w/ Array#to_h. If you don’t care if the keys of the hash are strings then you can simply do:
arr.transpose.to_h # => {"category"=>"category1", "subcat"=>"subcat1", "detail"=>"detail1"}
If you need the keys to be symbols then you’ll need to do a little more work:
arr.transpose.to_h.inject({}){|hash, (k,v)| hash[k.to_sym] = v; hash }
Please fix your example code, it doesn’t work. (BTW,
:category
is not equivalent to"category"
)Will there always be exactly two sub-arrays in
arr
?@Jordan, there could be a lot of arrays
Please edit your question to include an example of “a lot of arrays” and the expected output.
The problem is you keep overwriting the hash’s keys with the succeeding array. A hash only has unique keys. The documentation is clear about this:
A Hash is a dictionary-like collection of unique keys and their values.