2012-09-20 91 views
0

我有格式的表有日期時間列每個日期的哈希/陣列:如何創建的時間給出一個日期

2012-10-30 08:00:00 UTC 

我怎麼能創建一個數組或哈希那會按日期收集時間:

2012-10-30 
    8:00 
    9:00 
    13:00 
2012-11-02 
    8:00 
    9:00 

最後,我想有網絡輸出這樣的:

October 30, 2012 
    8:00 <reserve button> 
    9:00 <reserve button> 
    13:00 <reserve button> 

November 2, 2012 
    8:00 <reserve button> 
    9:00 <reserve button> 

我可以在圖如果我能正確設置數組,請將html部分除外。

回答

1

讓你的所有可用的時間戳從表中,例如:

available_times = SomeTable.select(:some_column).order(:some_column).all 

按日期建立一個哈希值:

@result = available_times.inject({}) do |m, timestamp| 
    date = timestamp.to_date 
    m[date] ||= [] 
    m[date] << timestamp 
    m 
end 

@result將是最新的可用時間的哈希值。

現在你可以做到這一點在你的觀點:

<% @result.each do |date, timestamps| -%> 
    <div><%= date.strftime("%B %-d, %Y") %></div> 
    <% timestamps.each do |timestamp| -%> 
    <%= timestamp.strftime("%k:%M") %> <input id='<%= timestamp.to_f%>' type='button' value='Reserve Button'/> 
    <br/> 
    <% end -%> 
<% end -%> 
+0

我想你說什麼,我得到這個錯誤:類型錯誤({}不是符號)任何想法? –

+0

對不起,'inject'後面有一個額外的'.each',它應該可以像更新一樣工作 – PinnyM

+0

那就是訣竅!謝謝。 –

1
sample = ["2012-10-28 08:30:00 UTC", 
      "2012-10-28 09:00:00 UTC", 
      "2012-11-30 09:15:00 UTC", 
      "2012-11-30 08:00:00 UTC"] 

sample.each_with_object(Hash.new{ |h, k| h[k] = [] }) do |d, h| 
    date = DateTime.parse(d) 
    h[date.strftime("%B %-d, %Y")] << date.strftime("%k:%M") 
end 
# => {"October 28, 2012"=>["8:30", "9:00"], "November 30, 2012"=>["9:15", "8:00"]} 
相關問題