在ruby中转换数组的嵌套哈希

时间:2018-04-05 14:08:16

标签: ruby-on-rails ruby

如何在ruby中嵌套哈希中转换数组

例如: 从

    {
       "errors": {
           "name": [
               "must be filled"
           ],
           "type": [
               "must be filled"
           ],
           "address": {
               "country_id": [
                   "must be filled"
               ]
           },
           "group": {
               "name": [
                   "is missing"
               ]
           },
           "contacts": {
               "2": {
                   "name": [
                       "must be filled"
                   ],
                   "phone": {
                       "0": {
                           "number": [
                               "must be filled"
                           ],
                           "email": [
                             "must be valid"
                           ]
                       }
                   }
               }
           }
       }
   }

   {
       "errors": {
           "name": "must be filled",
           "type": "must be filled",
           "address": {
               "country_id": "must be filled"
           },
           "group": {
               "name": "is missing"
           },
           "contacts": [
             {
               "name": "must be filled",
               "index": 2,
               "phone": [
                 {
                   "number": "must be filled",
                   "email": "must be valid",
                   "index": 0
                 }
               ]
           }
       }
   }

我想删除散列键(“2”,“0”)并将其转换为数组的散列。感谢

1 个答案:

答案 0 :(得分:0)

我尝试并以下列方式取得了成功。谢谢大家

def change(messages)
      result = {}
      array = []
      messages.each do |field, message|
        if message.is_a?(Hash)

          if field.is_a? Integer
            value = change(message)
            array.push(value.merge(index: field))
            result = array
          else
            value = change(message)
            result[field] = value
          end

        else
          result[field] = message.at(0)

        end
      end

      result
    end