Hi ,
i have the hash result is
[code]
puts @results
[{x=>"i8"}, {y=>"i58"}, {y=>"i6"}, {y=>"v5"}, {z=>"ci5"}, {z=>"i63"},
{w=>"cie201"}]
[/code]
from this @results hash ,i want to get new hash like below
I would rather say that it is an array of hashes that you want to
transform into an hash of arrays.
Please help me
First, you have to get the keys that will be in the resulting hash,
for example using inject (that here merge all the hashes into one big
hashes but loosing multiple entries of the same key):
Then iterate over the keys and populate the resulting hash by
selecting all the adequate values (that is those whose call don't
answer nil) and collecting them:
result_hash = {}
keys.each do |k|
result_hash[k] = arr.select {|h| h[k]}.collect {|h| h[k]}
end
p result_hash
puts @results
[{x=>"i8"}, {y=>"i58"}, {y=>"i6"}, {y=>"v5"}, {z=>"ci5"}, {z=>"i63"},
{w=>"cie201"}]
[/code]
from this @results hash ,i want to get new hash like below
The first line makes a Hash whose elements are automatically an empty
array if not already created. The second iterates over your original
hashes and adds to the values array for each key.
getting result is
{"w"=>["cie201"], "x"=>["i8"], "y"=>["i58", "i6", "v5"], "z"=>["ci5",
"i63"]}
but actual order of the elements placed is @results = [{"x"=>"i8"}, {"y"=>"i58"}, {"y"=>"i6"}, {"y"=>"v5"},
{"z"=>"ci5"}, {"z"=>"i63"}, {"w"=>"cie201"}]
In Ruby 1.9 Hash maintains insertion order so you should get what you expect. But generally hashes are not ordered. If you want to enforce a particular ordering then you need to explicitly sort.
Kind regards
robert
···
On 04/03/2010 12:24 PM, Lucky Nl wrote:
Hi , thankq to all,
every solution is working
but the problem is am not getting in order means
getting result is
{"w"=>["cie201"], "x"=>["i8"], "y"=>["i58", "i6", "v5"], "z"=>["ci5", "i63"]}
but actual order of the elements placed is @results = [{"x"=>"i8"}, {"y"=>"i58"}, {"y"=>"i6"}, {"y"=>"v5"},
{"z"=>"ci5"}, {"z"=>"i63"}, {"w"=>"cie201"}]