简体   繁体   English

在 Ruby 中迭代数天

[英]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我试图按照这里的例子: 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.或者,如果它不是您想要的连接字符串,您可以更改它的"#{init} #{date}"部分。

As a side note, using puts in ruby on rails won't print to the web page.附带说明一下,在轨道上使用puts中的 put 不会打印到 web 页面。 When you use <%= next_seven_days %> , the return value of that function is what will be printed to the page.当您使用<%= next_seven_days %>时,该 function 的返回值将打印到页面上。 The each function returns the range in parentheses. each function 返回括号中的范围。

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) ).您的问题是您正在查看返回值(因为each返回self将是(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.请注意,如果您在 erb 模板中打印到标准输出,则不会导致 output 出现在呈现的模板中。

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 =)您的 function 返回一个由 2011-07-07..2011-07-14 指定的枚举,该枚举显示在您的视图中,但您的 puts 打印到 STDOUT 这不是您的视图,而是您的服务器正在运行的控制台屏幕=)

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:)如果您希望您的视图显示 7 天的列表,您需要实际创建执行该操作的字符串并返回:)

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    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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