Rail map方法生成哈希数组

时间:2018-08-30 08:55:13

标签: ruby-on-rails arrays enumerator

我有一个哈希数组,并且正在使用map生成一个哈希数组。当我的数组有两个值但我想使用一个数组生成相同类型的结果时,我可以生成一个has数组。

我有一个数组:

 b =  [
    {
    id: 1,
    State: "Andhra Pradesh",
    Rural_Oct_16_Index_Final: 137.5,
    Rural_Oct_17_Index_Provisional: 143,
    Rural_Inflation_Rate_in_percentage: 4,
    Urban_Oct_16_Index_Final: 131.7,
    Urban_Oct_17_Index_Provisional: 135.6,
    Urban_Inflation_Rate_in_percentage: 3,
    Combined_Oct_16_Index_Final: 135.4,
    Combined_Oct_17_Index_Provisional: 140.3,
    Combined_Inflation_Rate_in_percentage: 3.6,
    created_at: "2018-08-30T05:01:58.000Z",
    updated_at: "2018-08-30T05:01:58.000Z"
    },
    {
    id: 2,
    State: "Bihar",
    Rural_Oct_16_Index_Final: 135.7,
    Rural_Oct_17_Index_Provisional: 138.7,
    Rural_Inflation_Rate_in_percentage: 2.2,
    Urban_Oct_16_Index_Final: 128.2,
    Urban_Oct_17_Index_Provisional: 131.4,
    Urban_Inflation_Rate_in_percentage: 2.5,
    Combined_Oct_16_Index_Final: 134.6,
    Combined_Oct_17_Index_Provisional: 137.6,
    Combined_Inflation_Rate_in_percentage: 2.2,
    created_at: "2018-08-30T05:01:58.000Z",
    updated_at: "2018-08-30T05:01:58.000Z"
    }
]

我使用以下代码:

 b.map do |el|
       { y: el['Rural_Oct_16_Index_Final'], label: el['State'] }
  end

我得到这个结果:

 [
   {
     y: 3.6,
     label: "Andhra Pradesh"
    },
    {
   y: 2.2,
  label: "Bihar"
  }
 ]

所以我的问题是我的数组何时只有一个值,如:

  [
    {
    id: 1,
    State: "Andhra Pradesh",
    Rural_Oct_16_Index_Final: 137.5,
    Rural_Oct_17_Index_Provisional: 143,
    Rural_Inflation_Rate_in_percentage: 4,
    Urban_Oct_16_Index_Final: 131.7,
    Urban_Oct_17_Index_Provisional: 135.6,
    Urban_Inflation_Rate_in_percentage: 3,
    Combined_Oct_16_Index_Final: 135.4,
    Combined_Oct_17_Index_Provisional: 140.3,
    Combined_Inflation_Rate_in_percentage: 3.6,
    created_at: "2018-08-30T05:01:58.000Z",
    updated_at: "2018-08-30T05:01:58.000Z"
    }
]

使用map方法,我想要这样的结果:

 [
   {
     y: 2.2,
     label: "Rural_Inflation_Rate_in_percentage"
    },
    {
   y: 128.2,
  label: "Urban_Oct_16_Index_Final"
  }
]

当我使用此代码时:

     b.map do |el|
    { y: el['Rural_Inflation_Rate_in_percentage'], label: "Rural_Inflation_Rate_in_percentage" },
     { y: el['Rural_Inflation_Rate_in_percentage'], label: "Rural_Inflation_Rate_in_percentage" }
end

删除逗号时出现此错误,我得到一个结果而没有错误。

有什么方法可以使用map方法来完成这项工作。

1 个答案:

答案 0 :(得分:1)

b.flat_map do |el|
  [{ y: el['Rural_Inflation_Rate_in_percentage'], label: "Rural_Inflation_Rate_in_percentage" },
     { y: el['Rural_Inflation_Rate_in_percentage'], label: "Rural_Inflation_Rate_in_percentage" }]
end