Home > Back-end >  How to convert a hash to proper formatted one in ruby?
How to convert a hash to proper formatted one in ruby?

Time:11-03

I have constructed a hash based upon the payload for an api request,


query = {
            'query_hash[0][condition]' => 'closed_at',
            'query_hash[0][operator]' => 'is_greater_than',
            'query_hash[0][type]' => 'default',
            'query_hash[0][value]' => '60',
            'query_hash[1][condition]' => 'country',
            'query_hash[1][operator]' => 'is_in',
            'query_hash[1][type]' => 'custom_field',
            'query_hash[1][value]' => ['India']
      }

Now I need the same hash in a different format like below for a different API request,

query_hash =>[
        {
              "condition" => 'closed_at',
              "operator" => 'is_greater_than',
              "type" => 'default',
              "value" => '60'
        },
        {
              "condition" => 'country',
              "operator" => 'is_in',
              "type" => 'custom_field',
              "value" => ['India']
        }
      ]

is there any built-in ruby function to achieve this?

CodePudding user response:

you can do this like below

query = {
            'query_hash[0][condition]' => 'closed_at',
            'query_hash[0][operator]' => 'is_greater_than',
            'query_hash[0][type]' => 'default',
            'query_hash[0][value]' => '60',
            'query_hash[1][condition]' => 'country',
            'query_hash[1][operator]' => 'is_in',
            'query_hash[1][type]' => 'custom_field',
            'query_hash[1][value]' => ['India']
      }

new_array =  Array.new
query.each do |k ,v| 
  keys = k.scan(/\[([0-9a-z]*)\]/).flatten
  index = keys.first.to_i
  new_array[index] ||= []
  new_array[index] << [keys.last, v]
end

puts new_array.map(&:to_h)

output

{"condition"=>"closed_at", "operator"=>"is_greater_than", "type"=>"default", "value"=>"60"}
{"condition"=>"country", "operator"=>"is_in", "type"=>"custom_field", "value"=>["India"]}

CodePudding user response:

I would do:

query = {
  'query_hash[0][condition]' => 'closed_at',
  'query_hash[0][operator]' => 'is_greater_than',
  'query_hash[0][type]' => 'default',
  'query_hash[0][value]' => '60',
  'query_hash[1][condition]' => 'country',
  'query_hash[1][operator]' => 'is_in',
  'query_hash[1][type]' => 'custom_field',
  'query_hash[1][value]' => ['India']
}

query_hash = []
query.each do |key, value| 
  index, new_key = key.scan(/(\d )\]\[(\w )/).flatten
  query_hash[index.to_i] ||= {}
  query_hash[index.to_i][new_key] = value
end

query_hash
#=> [{"condition"=>"closed_at", "operator"=>"is_greater_than", "type"=>"default", "value"=>"60"},
#    {"condition"=>"country", "operator"=>"is_in", "type"=>"custom_field", "value"=>["India"]}]
  • Related