Question

I have this:

balance = ["Date", "2014-03-17", "The voice", 1, "Date", "2014-03-18", "Argo", 1, "Date", "2014-03-19", "The voice", 0]    

When I use:

Hash[*balance]   

It gives me:

{"Date"=>"2014-03-19", "The voice"=>0, "Argo"=>1}    

Instead of:

   {"Date"=>"2014-03-17", "The voice"=>1, "Date"=>"2014-03-18", "Argo"=>1, "Date"=>"2014-03-19", "The voice"=>0}    

Why? (Sorry if it is obvious.)

Was it helpful?

Solution 3

As others have pointed out, the data structure you're asking for cannot exist as a Hash in Ruby, as it has duplicate keys. One possibility that may work for you is to generate an Array of Hashes:

balance = ["Date", "2014-03-17", "The voice", 1,
           "Date", "2014-03-18", "Argo", 1,
           "Date", "2014-03-19", "The voice", 0]

balance.each_slice(4).collect {|h| Hash[*h]}
# => [{"Date"=>"2014-03-17", "The voice"=>1},
#     {"Date"=>"2014-03-18", "Argo"=>1},
#     {"Date"=>"2014-03-19", "The voice"=>0}]

OTHER TIPS

According to Hash documentation:

A Hash is a dictionary-like collection of unique keys and their values.

There are multiple Dates, The voices.

{'key' => 'value1', 'key' => 'value2'}
# => {"key"=>"value2"}

How about using an array of hashes?

[{'key' => 'value1'}, {'key' => 'value2'}]

Yes, because in your array "The voice" and "Date" occurred multiple times, and Hash hold latest updated value of any of its key. As per your array last entries .."Date", "2014-03-19", "The voice", 0], causes your hash to hold latest values for the keys, "date" and "The voice".

What you are looking for is not possible, but you can get as [["Date", "2014-03-17"], ["The voice", 1],..]

Myarray=['a','b','c'] #Array initialize

hash={} #Hash initialize

#Access Array Element by index using each loop and put it in hash.

Myarray.each do |i|
 hash[Myarray.index(i)+1] = i.to_s
end

print hash 

Output:{1=>"a", 2=>"b", 3=>"c"}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top