Ruby on rails 如何在JSON数组中获取对象的索引?

Ruby on rails 如何在JSON数组中获取对象的索引?,ruby-on-rails,json,ruby,Ruby On Rails,Json,Ruby,我有如下格式的JSON数组,如何使用对象的键获取对象的位置索引 json = [ { "id"=>1, "user_name"=>"Mean Dean", "user_profile_id"=>"1", "amount"=>4 }, { "id"=>2, "user_name"=>"Mad Stan", "user_

我有如下格式的JSON数组,如何使用对象的键获取对象的位置索引

json = [
    {
        "id"=>1, 
        "user_name"=>"Mean Dean", 
        "user_profile_id"=>"1", 
        "amount"=>4
    },
    {
        "id"=>2, 
        "user_name"=>"Mad Stan", 
        "user_profile_id"=>"2", 
        "amount"=>7
    },
    {
        "id"=>3, 
        "user_name"=>"Jack Dean", 
        "user_profile_id"=>"3", 
        "amount"=>8
    }
]
例如,如果在本例1中给定了第一个元素的id,那么如果我想得到第一个元素的位置,我将如何进行操作。我读过这个方法,但不知道如何将它应用到JSON数组中


提前感谢您的帮助。

假设您有json变量中的数组,您可以使用:

要获取此元素的索引,可以使用:

要更新此对象,只需更新返回的哈希:

json.detect { |e| e['id'] == 1 }['amount'] = 500
#⇒ 500
json
#⇒ [
#  [0] {
#             "amount" => 500,  ⇐ !!!!!!!
#                 "id" => 1,
#          "user_name" => "Mean Dean",
#    "user_profile_id" => "1"
#  },
#  [1] {
#             "amount" => 7,
#                 "id" => 2,
#          "user_name" => "Mad Stan",
#    "user_profile_id" => "2"
#  },
#  [2] {
#             "amount" => 8,
#                 "id" => 3,
#          "user_name" => "Jack Dean",
#    "user_profile_id" => "3"
#  }
# ]

我需要这个位置,这样我就可以更新数量。如果存在具有给定id的对象,这将返回该对象。我该如何操纵它?你的问题标题与你的实际提问无关。请显示到目前为止您已尝试的内容,以及导致错误的原因。没有从上一个问题更新。对于愚蠢的错误,抱歉。
json.find_index { |e| e['id'] == 1 }
json.detect { |e| e['id'] == 1 }['amount'] = 500
#⇒ 500
json
#⇒ [
#  [0] {
#             "amount" => 500,  ⇐ !!!!!!!
#                 "id" => 1,
#          "user_name" => "Mean Dean",
#    "user_profile_id" => "1"
#  },
#  [1] {
#             "amount" => 7,
#                 "id" => 2,
#          "user_name" => "Mad Stan",
#    "user_profile_id" => "2"
#  },
#  [2] {
#             "amount" => 8,
#                 "id" => 3,
#          "user_name" => "Jack Dean",
#    "user_profile_id" => "3"
#  }
# ]