【问题标题】:Rails convert computed array of hashes into a nested arrayRails 将计算的哈希数组转换为嵌套数组
【发布时间】:2017-07-19 22:02:25
【问题描述】:

此查询响应包含经过计算的 delta 对,因此我不必在数据库中不必要地创建另一列。

records = [
  {"credential_id"=>1, "followers_count"=>10000, "created_at"=>"2017-02-26 18:50:20.654996", "delta"=>nil}, 
  {"credential_id"=>1, "followers_count"=>12000, "created_at"=>"2017-02-27 18:50:20.654996", "delta"=>2000}, 
  {"credential_id"=>1, "followers_count"=>15000, "created_at"=>"2017-02-28 18:50:20.654996", "delta"=>3000}
]

想要的结果:

deltas = [
  [2017-02-26 18:50:20.654996, nil],
  [2017-02-27 18:50:20.654996, 2000],
  [2017-02-28 18:50:20.654996, 3000]
]

尝试 -- 但是,我认为:delta 不是模型/表的一部分这一事实使我无法使用以下解决方案:.pluck(:created_at, :delta).values_at("created_at", "delta")

attributes = [:created_at, :delta]    

records.map do |record|
  attributes.map { |attr| record[attr] }
end

我已经用完了可以尝试的解决方案。你能帮我找到想要的结果吗?

【问题讨论】:

    标签: ruby-on-rails arrays postgresql hash attributes


    【解决方案1】:

    其实很简单:

    records.map { |h| [h['created_at'], h['delta']] }
     => [["2017-02-26 18:50:20.654996", nil], 
         ["2017-02-27 18:50:20.654996", 2000], 
         ["2017-02-28 18:50:20.654996", 3000]]
    

    在 Ruby 中,您可以通过在括号中传递键名来访问哈希值,就像在本例中一样。

    或者你可以使用Hash#values_at:

    records.map { |h| h.values_at('created_at', 'delta') }
    

    并得到相同的结果。

    【讨论】:

      【解决方案2】:

      用字符串替换属性符号:

      attributes = ['created_at', 'delta']    
      

      【讨论】:

        【解决方案3】:

        您只需要使用.map 遍历记录哈希,并将“created_at”和“delta”字段分配给一个新数组。 Array#map 允许您随时改变起始对象。

        records.map {|r| [r['created_at'], r['delta']]}
        

        来自文档:

        数组#map

        创建一个包含块返回值的新数组。

        Ruby Docs for map

        【讨论】:

          猜你喜欢
          • 2015-08-12
          • 1970-01-01
          • 2013-09-16
          • 1970-01-01
          • 2012-10-29
          • 2012-07-15
          • 2019-10-27
          • 2019-05-23
          • 2023-04-01
          相关资源
          最近更新 更多