I am trying to do a little experiment which has me stumped at the moment.
I create the new Hash
tt = Hash.new()
Then I add two hashes inside with keys:
tt.merge!(:in => Hash.new)
tt.merge!(:out => Hash.new)
So I have a hash that looks like this:
{
:in => {},
:out => {}
}
Now I have another hash of hashes called res that I iterate through and perform an IF statement on each one:
res.each do |x|
if x[:id] == nil
tt[:out].merge!(x)
else
tt[:in].merge!(x)
end
end
However this only attaches the last value of the previous hash to both out and in inside the new hash.
What I am trying to do is use the IF statement to put new hashes under the key of IN or OUT
So it ends up looking like:
{
:in => {{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 },{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }},
:out => {{:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }, {:1 => 1 ,:2 => 1 ,:3 => 1 ,:4 => 1 ,:5 => 1 }}
}
Also – should I be using Hashes for this or arrays?? I want to export it eventually as JSON.
For example, this works. But not sure if it is right:
tt = Hash.new(:in => Hash.new, :out => Hash.new)
tt.merge!(:in => Array.new)
tt.merge!(:out => Array.new)
ap tt.class
res.each do |x|
if x[:id] == nil
tt[:out] << x
else
tt[:in] << x
end
end
Thnaks
This isn’t possible. You’re talking about
{1,2,3,4,5}as a hash, but it’s not a hash, it’s an array. If you don’t have specific keys to associate with values, you don’t have hash-like data. Your second version which uses arrays is correct (except for your use ofmerge… see below).Also, if you want to add something to a hash, you should use the
[]operator, not repeatedly usemerge.For example, this is wrong:
What you want is either this:
or better, this:
The full and correct version of this could would look something like this: