"✓", "authenticity_token"=>"asdasdasd/Wi71c4U3aXasdasdasdpbyM-6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:03 25 4
gpt4 key购买 nike

修改参数散列中某些值的最佳方法是什么?例如,这是参数哈希。

{"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"}

所以从上面的params,我需要将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

我发现这种方法有点低效,因为我将不得不迭代指数时间,具体取决于散列的数量。谁能建议我更好的方法来做到这一点?

预先感谢您的帮助。

最佳答案

如果你想修改它们而不是返回一个新对象:

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

关于ruby-on-rails - 修改参数嵌套哈希的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57644722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com