2

我目前有一些 Ruby 代码可以创建这样的输出(在转换为 JSON 之后):

"days": [
    {
        "Jul-22": ""
    },
    {
        "Aug-19": ""
    }
],

我想要的是这样的输出:

"days": {
    "Jul-22": "",
    "Aug-19": ""
},

这是我的代码:

CalendarDay.in_the_past_30_days(patient).select(&:noteworthy?).collect do |noteworthy_day|
  { noteworthy_day.date.to_s(:trends_id) => "" }
end

换句话说,我想要一个散列而不是散列数组。这是我丑陋的解决方案:

days = {}
CalendarDay.in_the_past_30_days(patient).select(&:noteworthy?).each do |noteworthy_day|
  days[noteworthy_day.date.to_s(:trends_id)] = ""
end 
days

不过,这似乎很不像红宝石。有人可以帮助我更有效地做到这一点吗?

4

2 回答 2

2
Hash[
  CalendarDay.in_the_past_30_days(patient).select(&:noteworthy?).collect { |noteworthy_day|
    [noteworthy_day.date.to_s(:trends_id), ""]
  }
]

或者...

CalendarDay.in_the_past_30_days(patient).select(&:noteworthy?).each_with_object(Hash.new) { |noteworthy_day, ndays|
  ndays[noteworthy_day] = ""
}
于 2013-08-20T15:53:59.670 回答
0

这是一个量身定制的问题Enumerable#inject

CalendarDay.in_the_past_30_days(patient).select(&:noteworthy?).inject({}) do |hash, noteworthy_day|
    hash[noteworthy_day.date.to_s(:trends_id)] = ''
    hash
end
于 2013-08-20T17:54:59.657 回答