优雅地从数组创建哈希

时间:2013-08-20 15:43:14

标签: ruby

我目前有一些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
但是,这似乎非常无趣。有人可以帮助我更有效地做到这一点吗?

2 个答案:

答案 0 :(得分: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] = ""
}

答案 1 :(得分: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