ashr81 ashr81 - 1 year ago 73
Ruby Question

Ruby or Ruby on Rails group_by on dynamically changing parameters

I want to change group_by parameters based on user input.
Data on which i am going to group:

result = [{"result_1"=>"01","result_2"=>"August","result_3"=>"2016","result_4"=>264},{"result_1"=>"02","result_2"=>"August","result_3"=>"2016","result_4"=>49},{"result_1"=>"03","result_2"=>"August","result_3"=>"2016","result_4"=>53}]

I know how a ruby group_by works with multiple parameters.

To group_by on result_1 and result_2.It can be done this way:

result.group_by{|h| [h["result_1"],h["result_2"]}

Above code groups the data based on result_1 and result_2.Here the parameters are hard_coded.
I want group_by based on parameters passed dynamically.As

dynamic_parameter = ["result_3","result_4"]

I want group_by to be as

result.group_by{|h| [h["result_3"],h["result_4"]]}

i want to do it as roughly:

dynamic_parameters.each do |parameter|
result.group_by{|h| [h[parameters]}

or similar to:

result.group_by{|h| [h[parameters[0]],h[parameters[1]]}

These result_3 and result_4 parameters are based on dynamic_parameter array values.

Note: Group_by should vary based on the array elements.

Answer Source

If I understood your question correctly then something like this would do the job:

result.group_by do |h|{ |p| h[p] }

Or one-liner:

result.group_by { |h| h.values_at(*dynamic_parameters) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download