Ruby 在Rails中使用映射获取空值

Ruby 在Rails中使用映射获取空值,ruby,Ruby,当我在映射内使用if条件时,得到的是空值。我有一个数组,我在其中循环 我的第一个数组是: [ { id: 5, Vegetables: "Cabbage", Area: 39, Production: 695.33, Year: 2014, created_at: "2018-07-18T06:23:11.000Z", updated_at: "2018-07-18T06:23

当我在映射内使用if条件时,得到的是空值。我有一个数组,我在其中循环

我的第一个数组是:

[
    {
        id: 5,
        Vegetables: "Cabbage",
        Area: 39,
        Production: 695.33,
        Year: 2014,
        created_at: "2018-07-18T06:23:11.000Z",
        updated_at: "2018-07-18T06:23:11.000Z"
    },
    {
        id: 12,
        Vegetables: "Bittergourd",
        Area: 9.71,
        Production: 67.25,
        Year: 2014,
        created_at: "2018-07-18T06:23:11.000Z",
        updated_at: "2018-07-18T06:23:11.000Z"
    },
    # .....
]
这是我的数组,我使用以下代码循环:

ji1 = ["Cabbage","Bittergourd"]
hash_data = ji1.map do |col|
  dataset = col.to_s.gsub("_"," ")
  {
    type: views,
    legendText: dataset,
    showInLegend: true,
    dataPoints: b.reject{ |x| x["Districts"] == "Bihar" }.map do |el|
      if el["Vegetables"] == "Bittergourd"
        { y: el["Area"], label: el["Year"] }
      end
    end
  }
end
在本例中,
b
是我的数组,我得到这个值。我想要这样的结果:

[
  {
    type: "column",
    legendText: "Cabbage",
    showInLegend: true,
    dataPoints: [
      {
        y: 9.7,
        label: 2014
      }
    ]
  },
  {
    type: "column",
    legendText: "Bittergourd",
    showInLegend: true,
    dataPoints: [
      {
        y: 39,
        label: 2014
      }
      # .....
    ]
  }
]

当我运行我的循环时,我得到一个
null
值。是否有任何方法可以使用数组中的
map
创建上述结果?

使用您提供的数据,并删除视图,因为我不知道该变量来自何处。。。试试这段代码。我相信它实现了你想要做的

    grouped_data = b.group_by{ |data| data[:Vegetables]}

    grouped_data.map{ |vegetable, values| 
        dataset = vegetable.to_s.gsub("_"," ")
        {

          legendText: dataset,
          showInLegend: true,
          dataPoints: values.map { |value|
            { y: value[:Area], label: value[:Year] }
          }
        }
     }
更新

不使用
分组依据

vegetables_hash = Hash.new
b.each { |data| 
    dataset = data[:Vegetables].to_s.gsub("_"," ")
    vegetables_hash[dataset] ||= { legendtext: dataset, showInLegend: true, dataPoints: []}
    vegetables_hash[dataset][:dataPoints].push({ y: data[:Area], label: data[:Year] })
}
蔬菜\u hash
以所需格式按蔬菜分组数据。 最后一步:

vegetables_hash.values

我不知道有些信息应该从哪里来。例如,变量
view
从何而来:
type:views
?你可以把任何不重要的东西都放进去为什么不在每次迭代时循环遍历散列并向其添加一个额外的键?这个示例代码对我来说没有意义,因此在不查看变量(如视图)的声明位置的情况下,无法帮助您获得准确的代码。实际数据是如果
view
type:views
“不重要”,请将示例更改为完整的示例,而不是要求每个想运行您的代码的读者以某种任意的方式更改代码。如果
b
是你的“第一个数组”,写
b=[{id:5,…}
。更一般地说,当你给出一个例子时,让所有的值都是有效的Ruby对象,给每个输入对象分配一个变量(以便读者可以在答案和注释中引用这些变量),让例子尽可能简洁,并显示你想要的结果(一个Ruby对象)。最后,有一个对象
nil
,但是“null”没有定义。是的,它可以工作。有没有办法在没有分组的情况下分组数据呢?在这里。我更新了答案,以便不使用
group\u by
。有很多方法可以做到这一点。我希望这些方法能有所帮助。