简体   繁体   中英

Iterating over days in Ruby

I've tried the following:

def next_seven_days
  today = Date.today
  (today .. today + 7).each { |date| puts date } 
end 

But this just gives me the first and last date. I can't figure out how to get all the ones in between.

I was trying to follow the example here: http://www.whynotwiki.com/Ruby_/_Dates_and_times

I think you want something more like this:

def next_seven_days
  today = Date.today
  (today .. today + 7).inject { |init, date|  "#{init} #{date}" } 
end

In this case, the return value is a concatenated string containing all the dates.

Alternatively, if it's not a concatenated string you want, you could change the "#{init} #{date}" part of it.

As a side note, using puts in ruby on rails won't print to the web page. When you use <%= next_seven_days %> , the return value of that function is what will be printed to the page. The each function returns the range in parentheses.

Your code will definitely print all eight days to stdout. Your problem is that you're looking at the return value (which since each returns self will be (today.. today + 7) ).

Note that if you print to stdout inside an erb template, that won't cause the output to show up in the rendered template.

Your function RETURNS an enumeration designated by 2011-07-07..2011-07-14 which is displayed in your view, but your puts prints to STDOUT which is not going to be your view, but the console screen your server is running in =)

If you want your view to show a list of the seven days, you need to actually create the string that does that and RETURN that:)

def next_seven_days
  outputstr = ""
  today = Date.today
  (today..(today+7.days)).each { |date| outputstr += date.to_s }
  return outputstr 
end 
def next_seven_days
  today = Date.today
  (today..(today+7.days)).each { |date| puts date } 
end 

Use the "next" method

        def next_seven_days
          today= Date.today
          7.times do 
             puts today
             today=today.next
           end
        end    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM