修改参数嵌套哈希的最佳方法是什么?

What is the best way to modify params nested hash?

修改参数散列中的某些值的最佳方法是什么?例如,这是 params hash.

{"utf8"=>"✓", "authenticity_token"=>"asdasdasd/Wi71c4U3aXasdasdasdpbyMZLYo1sAAmssscQEkv0WsWBDyslcWJxUZ2pPKOQFmJoVZw==", "user_api"=>{"user"=>"asdak", "name"=>"asdada", "friends_attributes"=>{"1566720653776"=>{"_destroy"=>"false", "player_name"=>"asda", "player_type"=>"backside", "user_interest"=>"cricket,football,basketball"}, "1566720658089"=>{"_destroy"=>"false", "player_name"=>"asdad", "player_type"=>"forward", "user_interest"=>"table_tennis,chess"}}}, "commit"=>"Save User Data"}

所以从上面的参数,我需要修改user_options值到一个数组。

params.each do |key, user_api_hash|
    if key == "user_api"
      user_api_hash.each do |key, friend_hash|
        if key == "friends_attributes"
          friend_hash.each do |key, value|
            value["user_interest"] = value["user_interest"].split(',')
          end
        end
      end
    end
  end

我发现这种方法效率不高,因为我将不得不迭代指数次,具体取决于散列的数量。任何人都可以建议我更好的方法吗?

预先感谢您的帮助。

如果您想修改它们而不是return创建一个新对象:

(params.dig(:user_api, :friends_attributes) || []).each do |_, attributes|
  attributes['user_interest'] = attributes['user_interest'].split(',')
end
  • dig 可以访问散列内部的键以及它们内部的其他散列内部的键。
  • 如果某个键不存在,那么它将return nil,在这种情况下使用一个空数组,它将迭代0次。
  • 在用户属性中,您可以通过简单的赋值来修改它们。