Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 351
Slick23 Avatar asked Jul 07 '11 18:07

Slick23


4 Answers

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.

like image 90
Aaron Avatar answered Sep 19 '22 11:09

Aaron


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.

like image 22
sepp2k Avatar answered Sep 19 '22 11:09

sepp2k


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 
like image 32
David Nguyen Avatar answered Sep 23 '22 11:09

David Nguyen


def next_seven_days
  today = Date.today
  (today..(today+7.days)).each { |date| puts date } 
end 
like image 42
tybro0103 Avatar answered Sep 19 '22 11:09

tybro0103