Home > Software engineering >  Rails: Retrieve keys and values from hashmap
Rails: Retrieve keys and values from hashmap

Time:02-01

I'm trying to retrieve two separate values with dates for a chart...

 @a = Applications.all.group_by_month(:created_at, format: '%b %y').count
 @b = Secondary_Applications.all.group_by_month(:created_at, format: '%b %y').count

I mapped it like this...

keys = [@a, @b].flat_map(&:keys).uniq

@ab_final = keys.map do |k| 
                {k => [{applications_one: @a[k] || 0}, 
                {applications_two: @b[k] || 0}]}
              end

This gives...

[
{"May 21"=>
  [{:applications_one=>20}, {:applications_two=>0}]},

{"Jun 21"=>
  [{:applications_one=>15}, {:applications_two=>0}]},

{"Jul 21"=>
  [{:applications_one=>8}, {:applications_two=>11}]},

 {"Aug 21"=>
  [{:applications_one=>1}, {:applications_two=>2}]} 
] 

I don't know how to get the values from this point. How would you extract the date keys and values like...?

Expected output:

applications_one [20, 15, 8, 1]

applications_two [0, 0, 11, 2]

dates [May 21, Jun 21, Jul 21, Aug 21]

ty

CodePudding user response:

Is that what you want to achieve?

arr = [
  {"May 21"=>
    [{:applications_one=>20}, {:applications_two=>0}]},

  {"Jun 21"=>
    [{:applications_one=>15}, {:applications_two=>0}]},

  {"Jul 21"=>
    [{:applications_one=>8}, {:applications_two=>11}]},

   {"Aug 21"=>
    [{:applications_one=>1}, {:applications_two=>2}]}
  ]

applications_one = []
applications_two = []
dates = []

arr.each do |hash|
  hash.values.flatten.each do |element|
    applications_one << element[:applications_one] if element.key?(:applications_one)
    applications_two << element[:applications_two] if element.key?(:applications_two)
  end
  dates << hash.keys.first
end

2.7.3 :027 > applications_one
 => [20, 15, 8, 1] 
2.7.3 :028 > applications_two
 => [0, 0, 11, 2] 
2.7.3 :029 > dates
 => ["May 21", "Jun 21", "Jul 21", "Aug 21"] 
2.7.3 :030 > 

CodePudding user response:

I would do it a bit different. Would start by structuring the data this way:

@ab_final = keys.map do |k| 
    {date: k, applications_one: @a[k] || 0, applications_two: @b[k] || 0}}
end

This should give you:

@ab_final = [
    {:date=>"May 21", :applications_one=>20, :applications_two=>0},
    {:date=>"Jun 21", :applications_one=>15, :applications_two=>0},
    {:date=>"Jul 21", :applications_one=>8, :applications_two=>11},
    {:date=>"Aug 21", :applications_one=>1, :applications_two=>2} 
]

And then you would get your expected outputs like this:

dates = @ab_final.map{|d| d[:date]}
=> ["May 21", "Jun 21", "Jul 21", "Aug 21"]

applications_one = @ab_final.map{|d| d[:applications_one]}
=> [20, 15, 8, 1]

applications_two = @ab_final.map{|d| d[:applications_two]}
=> [0, 0, 11, 2]
  •  Tags:  
  • Related