修改数组和哈希的嵌套哈希

时间:2016-11-21 08:45:30

标签: ruby

{"8933"=>
  [{"id"=>419,
    "game_id"=>8933,
    "user_id"=>1,
    "line"=>21,
    "created_at"=>Mon, 21 Nov 2016 02:27:16 EST -05:00,
    "updated_at"=>Mon, 21 Nov 2016 02:27:16 EST -05:00}],
 "8690"=>
  [{"id"=>401,
    "game_id"=>8690,
    "user_id"=>1,
    "line"=>#<BigDecimal:7fdd42d96670,'-0.5E0',9(18)>,
    "created_at"=>Wed, 16 Nov 2016 21:55:59 EST -05:00,
    "updated_at"=>Wed, 16 Nov 2016 21:55:59 EST -05:00}]}

我需要保留这个确切的结构,只需将第一个"line"的值更改/更新为任何内容,让我们说20。它始终是我需要更新/修改的相同位置。我尝试了一堆Hash#methods只是为了遇到语法错误或改变现有结构。谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案,它不会修改原始数据并创建新的哈希值。

2,3,5,6,9
1,5,6,9,4,5
9,5

如果您真的只想修改data = { "8933"=> [ { "id"=>419, "game_id"=>8933, "user_id"=>1, "line"=>21, "created_at"=>"Mon, 21 Nov 2016 02:27:16 EST -05:00", "updated_at"=>"Mon, 21 Nov 2016 02:27:16 EST -05:00" } ], "8690"=> [ { "id"=>401, "game_id"=>8690, "user_id"=>1, "line"=>-5, "created_at"=>"Wed, 16 Nov 2016 21:55:59 EST -05:00", "updated_at"=>"Wed, 16 Nov 2016 21:55:59 EST -05:00" } ] } # Use deep_copy if you use Ruby only. Use data.deep_dup if you use Rails def deep_copy(o) Marshal.load(Marshal.dump(o)) end modified_data = deep_copy(data) modified_data.each{|n,array| array.each{|ids| ids["line"] = "whatever" } } require 'pp' pp modified_data puts "-----" pp data # {"8933"=> # [{"id"=>419, # "game_id"=>8933, # "user_id"=>1, # "line"=>"whatever", # "created_at"=>"Mon, 21 Nov 2016 02:27:16 EST -05:00", # "updated_at"=>"Mon, 21 Nov 2016 02:27:16 EST -05:00"}], # "8690"=> # [{"id"=>401, # "game_id"=>8690, # "user_id"=>1, # "line"=>"whatever", # "created_at"=>"Wed, 16 Nov 2016 21:55:59 EST -05:00", # "updated_at"=>"Wed, 16 Nov 2016 21:55:59 EST -05:00"}]} # ----- # {"8933"=> # [{"id"=>419, # "game_id"=>8933, # "user_id"=>1, # "line"=>21, # "created_at"=>"Mon, 21 Nov 2016 02:27:16 EST -05:00", # "updated_at"=>"Mon, 21 Nov 2016 02:27:16 EST -05:00"}], # "8690"=> # [{"id"=>401, # "game_id"=>8690, # "user_id"=>1, # "line"=>-5, # "created_at"=>"Wed, 16 Nov 2016 21:55:59 EST -05:00", # "updated_at"=>"Wed, 16 Nov 2016 21:55:59 EST -05:00"}]} 的第一次出现,您可以这样做:

line