在特定位置向数组哈希红宝石添加值

问题描述

我有一个如下所示的哈希响应对象:

jsonResponse = {:json=>{"reply"=>[{"person"=>"abc","roll_no"=>"1234","location"=>"loc1","score"=>"1"},{"person"=>"def","roll_no"=>"1235","location"=>"loc2","score"=>"2"},{"person"=>"fgh","roll_no"=>"1236","location"=>"loc3","score"=>"3"}]},:status=>200}

我必须在每个特定的回复数组对象的特定位置添加一个键值对,以便将响应转换为这样的内容,现在使其变得更简单,让我们尝试添加特定位置的samke键值对:

jsonResponse = {:json=>{"reply"=>[{"person"=>"abc","new_value => "new_result",:status=>200}

这是我尝试过的,我通过jsonResponse运行.each:

jsonResponse[:json]['reply'].each do |object|
               objectArray = object.to_a
               insert_at = objectArray.index(objectArray.assoc('score'))
               object = Hash[objectArray.insert(insert_at,['new_value','new_result'])]
               print("\n\nTest\n\n")
               print object
      end
    print("\n\nFinal Response\n\n")
    print jsonResponse

我正在打印的

对象 具有所需的响应,但是在 jsonResponse 中没有更新

这是上面代码片段的输出


Test

{"person"=>"abc","new_value"=>"new_result","score"=>"1"}

Test

{"person"=>"def","score"=>"2"}

Test

{"person"=>"fgh","score"=>"3"}

Final Response

{:json=>{"reply"=>[{"person"=>"abc",:status=>200}

第二季度。另外,如代码段所示, insert_at 逻辑的工作方式是在我们指定的位置之前添加,例如,它在得分键之前添加,是否存在我可以编写的逻辑,该逻辑在指定键之后的位置而不是之前?

感谢大家的努力

解决方法

我们得到了三个对象。

jsonResponse = {
  :json=>{
    "reply"=>[
      {"person"=>"abc","roll_no"=>"1234","location"=>"loc1","score"=>"1"},{"person"=>"def","roll_no"=>"1235","location"=>"loc2","score"=>"2"},{"person"=>"fgh","roll_no"=>"1236","location"=>"loc3","score"=>"3"}
    ]
  },:status=>200
}

key_value_pair_to_add = { 'new_value'=>'new_result' }
key_to_precede = 'location'

然后我们按如下所示修改jsonResponse

keys_to_shift = jsonResponse[:json]['reply'][0].keys.
  drop_while { |k| k != key_to_precede }        
  #=> ["location","score"]
jsonResponse[:json]['reply'].each do |h| 
  h.update('new_value'=>'new_result')
  keys_to_shift.each { |k| h.update(k=>h.delete(k)) }
end
jsonResponse
  #=> {
  #     :json=>{
  #       "reply"=>[
  #         {"person"=>"abc","new_value"=>"new_result",#          "location"=>"loc1",#         {"person"=>"def",#          "location"=>"loc2",#         {"person"=>"fgh",#          "location"=>"loc3","score"=>"3"}
  #       ]
  #     },#     :status=>200
  #   }

请参见Hash#update(又名merge!)和Hash#delete

h.delete('location')

'location'=>'locX'中移除键值对h并返回locX,然后

h.update('location'=>'locX')

将该键值对返回到哈希的末尾。对keys_to_shift中的每个键重复此操作。

,

举一个简单的例子:

# define order 
order = [:first,:second,:third]
# the hash you want to order by
json = { :third=>"3",:second=>2,:first=>1 }

result = json.sort_by { |k,_| order.index(k) }.to_h

那么结果将是{:first=>1,:third=>"3"}