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

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... ^_^

Thanks to reply. I had done this by

final_data['gate_passes'] = results.group_by{|r| r['gate_pass_type_id']}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.