How can I loop through each of the days of a given week in Ruby?

I define Monday and Friday using the following:

@monday = Date.today.at_beginning_of_week

@friday = 5.days.since(@monday)

      

But I really need any day to loop through Monday, Tuesday, Wednesday and take that date and put the output in a column.

<th>Monday</th>
<th>Tuesday</th>
etcetera

      

This line, for example, will be:

<tr><td>method_with_arg(monday)</td><td>method_with_arg(tuesday)</td><td>method_with_arg(wednesday)</td></tr>

      

Here value is the method that accepts the args date.

What's the cleanest way to do this?

Thanks.

+2


a source to share


4 answers


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, a.strftime

you can call any other method that receives a date and returns a string, for example mails_sent_on(a)

, etc. You can also use yield a

to pass time-dependent logic using a 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 the lines from the method dates_week

:

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 shape you need.

+5


a source


I'm just using Plain Old Ruby Objects, but I think if you want to keep things DRY, you want to separate the weekday logic from what you use on weekdays.



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

      

+1


a source


I would go one step further than Andrew and it took 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

      

+1


a source


Simplest solution I could think of:

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

      

This should do the trick

0


a source







All Articles