添加和删​​除数组中的哈希值

时间:2014-12-25 11:25:47

标签: ruby-on-rails arrays json sorting

我正在尝试为日历系统创建后端。日历只是Event的列表。我正在尝试将其组织成合理的JSON响应。我希望复制的结构将是这样的

eventsList = [
  { 'year' => 2014,
     'events' => [{event data hash 1}, 
                  {event data hash 2}]
  },
  { 'year' => 2015,
     'events' => [{event data hash 1}, 
                  {event data hash 2}]
  }
]

我在尝试向正确的数组添加事件时遇到问题。下面我有Event.all,我正在尝试对列表进行排序。

events = Event.all
eventList = []


events.each do |event|
    #Creates a hash of the current event info
    eventInfo = {'description' => event.description, 'startdate' => event.startdate}

    eventMonthNumber = event.startdate.strftime('%m').to_i
    eventMonthName = event.startdate.strftime('%B')
    eventYearNumber = event.startdate.strftime('%Y').to_i

    # Adds year to eventList if it isn't present
    unless eventList.include?(eventYearNumber)
        eventList << {'year' => eventYearNumber, 'events' => []}
    end

    # Tries to find current year hash in array and add to event key
    currentYear =  eventList.select {|event| event['year'] == eventYearNumber}
    currentYear['events'] << eventInfo
end

我收到错误no implicit conversion of String into Integer。我不完全确定eventList.select是否是正确的方法

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

虽然我已经离开了这个当前的结构,但是它的工作变化是交换

 eventList.select

 eventList.detect

Select返回一个数组(?)并且detect返回一个项目。

圣诞快乐!