【问题标题】:How to "trasform" an array of hash so that you can customize logic to access its data?如何“转换”散列数组以便您可以自定义逻辑来访问其数据?
【发布时间】:2011-07-13 21:51:47
【问题描述】:

我正在使用 Ruby on Rails 3,我想“转换”以下数组,以便我可以使用我的自定义逻辑来访问其数据。

这是我必须从中构建一个新数组的原始数组

[
  {
    "account" => {
       "id"   => 45, 
       "name" => "Test_name", 
       "..."  => ..."
     }
   }, 
   {
     "other"  => {
       "sub_other" => {...}
     }
   }
]

我想改变上面的数组,以便我可以在我的控制器中做类似的事情

array_name[45]
# => {
       "name" => "Test_name", 
       "..."  => ..."
      }

但仅适用于 account 哈希other 哈希应该保持不变。

如何继续构建新阵列?

【问题讨论】:

  • 如果你只是为了方便地访问控制器中的一个数据结构而将一个大数据结构转换为另一个数据结构,那么效率非常低。可能有更好的方法。第一个数组来自什么?
  • @Mark Thomas 这是“帐户”。
  • 如果 Account 是 ActiveRecord 模型,则根本不需要创建第一个数组。使用诸如 find() 之类的 ActiveRecord 方法来获取您需要的内容。
  • @Mark Thomas 我还使用需要数组才能工作的“Will_paginate”插件。另外,如何使用 'where' 语句找到 ActiveRecord 并返回哈希?

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


【解决方案1】:

如果我正确理解您的要求,我认为您最好构建一个从帐户 ID 到帐户数据的哈希。也许这样的事情会起作用:

arr = [
  {
    "account" => {
       "id"   => 45, 
       "name" => "Test_name", 
       "..."  => "..."
     }
   }, 
   {
     "other"  => {
       "sub_other" => "..."
     }
   }
]

account_hashes = arr.select {|item| item.keys.first == "account"}

answer = account_hashes.inject({}) do |acc, item| 
    acc[item["account"].delete("id")] = item["account"]
    acc
end

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 2020-08-07
    • 2015-04-13
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多