【问题标题】:Ruby: replace the values in a key-value pair of an array of hashes with the values from a 2nd arrayRuby:用第二个数组中的值替换散列数组的键值对中的值
【发布时间】:2012-07-01 23:32:18
【问题描述】:

在 Ruby 中,我有一个哈希数组和一个数组。在我的哈希数组中,我想用我的第二个数组中的值替换其中一个键值对中的值。实现此目的最干净的方法是什么?

示例(我想用我的第二个数组中的值替换“total”的值):

哈希数组:

 [{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":9}]

数组:

 [1, 10]

所需的哈希数组:

 [{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":10}]

【问题讨论】:

    标签: ruby-on-rails ruby arrays ruby-on-rails-3 hash


    【解决方案1】:
    array.each_with_index {|e,i| hash_array[i]["total"] = e}
    

    【讨论】:

    • 这似乎对我不起作用。当我运行 array = [1, 10]hash_array = [{:date => "2012-05-27", :total => 1},{:date => "2012-05-27", :total => 9}]array.each_with_index {|e,i| hash_array[i]["total"] = e} 时,结果是 [1, 10] 而我正在寻找的是 [{:date => "2012-05-27", :total => 1},{:date => "2012-05-27", :total => 10}]
    • 用 :total 替换“total”,因为 symbol 不是字符串。在您的问题中有字符串“total”。
    • 嗯,我不确定我做错了什么。我仍然得到相同的结果:array = [1, 10]hash_array = [{:date => "2012-05-27", :total => 1},{:date => "2012-05-27", :total => 9}]array.each_with_index {|e,i| hash_array[i][:total] = e} 结果是 [1, 10]
    【解决方案2】:
    hashes = [{date: "2012-05-27", total: 1},{date: "2012-05-28", total: 9}] #unquoted keys
    values = [1,10]
    
    hashes.zip(values){|h,v| h[:total] = v}
    p hashes #=>[{:date=>"2012-05-27", :total=>1}, {:date=>"2012-05-28", :total=>10}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 2014-07-03
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2010-12-07
      • 1970-01-01
      相关资源
      最近更新 更多