How can I loop through each of the days of a given week in Ruby?
I am defining monday and friday using the following:
开发者_JAVA百科@monday = Date.today.at_beginning_of_week
@friday = 5.days.since(@monday)
But I actually need, for any given day, to loop through Monday, Tuesday, Wednesday and take that date and put the output into a column.
<th>Monday</th>
<th>Tuesday</th>
etcetera
A given row, for example, would be:
<tr><td>method_with_arg(monday)</td><td>method_with_arg(tuesday)</td><td>method_with_arg(wednesday)</td></tr>
This is where value is a method that takes args date.
What's the cleanest way to do this?
Thanks.
def dates_week(d)
(d.beginning_of_week...d.beginning_of_week+5).map{|a|
"<td>#{a.strftime('%F')}</td>"
}.join
end
dates_week Date.today
#=> "<td>2010-05-17</td><td>2010-05-18</td><td>2010-05-19</td><td>2010-05-20</td><td>2010-05-21</td>"
Instead of a.strftime
you can call any other method receiving Date and returning string, such as mails_sent_on(a)
etc. You can also use yield a
there to pass your date-dependent logic using block:
def dates_week(d)
(d.beginning_of_week...d.beginning_of_week+5).map{|a|
yield a
}.join
end
dates_week(Date.today) { |d|
"<td>#{mails_sent_on(d)}</td>"
}
or, keeping strings out of dates_week
method:
def dates_week(d)
(d.beginning_of_week...d.beginning_of_week+5).map{|a|
yield a
}
end
dates_week(Date.today) { |d|
mails_sent_on(d)
}.join(', ')
or whatever form you need.
I just use Plain Old Ruby Objects, but I think if you want to keep things DRY, you'd want to separate out the logic of weekdays from what you're using the weekdays for.
def dates_week(d)
d.beginning_of_week...(d.beginning_of_week+5)
end
dates_week(Date.today).map {|a|
"<td>#{a.strftime('%F')}</td>"
}.join
I'd go even one step further than Andrew and have it take a block:
def dates_week(d, delim)
"<tr>" + (d.beginning_of_week...(d.beginning_of_week+5)).map do |day|
"<#{delim}> #{yield(day)} </#{delim}>"
end.join + "</tr>"
end
dates_week(Date.today, "th") {|d| d.strftime("%A")} # => <tr><th>Monday</th><th>Tuesday</th>...
dates_week(Date.today, "td") {|d| some_function(d)} #first row
The simplest solution I could think of would be:
first_day = Date.today.at_beginning_of_week
days = 7.times.map {|x| first_day + x.days }
days.each do |day|
puts "<td>" + func(day) + "</td>"
end
That should do the trick
精彩评论