0

Hi all,
This is my array of hash

[{"gate_pass_type_id"=>2, "tag"=>0, "total"=>2000}, {"gate_pass_type_id"=>125, "tag"=>0, "total"=>300}, {"gate_pass_type_id"=>661, "tag"=>0, "total"=>750}, {"gate_pass_type_id"=>661, "tag"=>2, "total"=>100}]

I want to convert it into
[2 => { "0"=> 2000},
125=> {"0"=>300},
661=>{"0" =>750, "2"=>100}]

Is any simple way without using so much loops

2
Contributors
2
Replies
20
Views
5 Months
Discussion Span
Last Post by rchawdhari
0

Hello, maybe you want to use something like this:

#!/usr/bin/env ruby

h = [{"gate_pass_type_id"=>2, "tag"=>0, "total"=>2000}, {"gate_pass_type_id"=>125, "tag"=>0, "total"=>300}, {"gate_pass_type_id"=>661, "tag"=>0, "total"=>750}, {"gate_pass_type_id"=>661, "tag"=>2, "total"=>100}]

n = Hash.new

h.each do |k|
    gate  = k.values[0]
    tag   = k.values[1]
    total = k.values[2]

    if(n.has_key?(gate) == true)
        n[gate] = n[gate].merge({ tag => total })
    else
        n[gate] = { tag => total }
    end
end

puts n

I also suggest for you to wait for more appropriated suggestions, as I have not used Ruby in the last decade... ^_^

0

Thanks to reply. I had done this by

final_data['gate_passes'] = results.group_by{|r| r['gate_pass_type_id']}
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.