开发者

Every other date

I have this logic to print out the dates

def get_y_axis
 dates = ""
  ed = Date.today
  sd = Date.today - 30
  sd.upto(ed) do |date|
  dates << date.strftime("%b %d")
  dates << "|"
end
 开发者_开发百科return dates
end

It prints like this

=> "Jan 24|Jan 25|Jan 26|Jan 27|Jan 28|Jan 29|Jan 30|Jan 31|Feb 01|Feb 02|Feb 03|Feb 04|Feb 05|Feb 06|Feb 07|Feb 08|Feb 09|Feb 10|Feb 11|Feb 12|Feb 13|Feb 14|Feb 15|Feb 16|Feb 17|Feb 18|Feb 19|Feb 20|Feb 21|Feb 22|Feb 23|"

The problem is I only need every other day...not every day Any ideas


Mark's solution is fine, but just wanted to show each_with_index method

def get_y_axis
  dates = []
  ed = Date.today
  sd = Date.today - 30
  (sd..ed).each_with_index do |date, i|
    dates << date.strftime("%b %d") if i % 2 == 0
  end
  dates.join("|")
end

Also, in your solution, you will get a "|" appended after the last date. I guess you dont want that.


I think that there's probably a more elegant solution, but this should do the trick:

def get_y_axis
  dates = ""
  ed = Date.today
  sd = Date.today - 30
  i = 0
  sd.upto(ed) do |date|
    if i % 2 == 0
      dates << date.strftime("%b %d")
      dates << "|"
    end
    i += 1
  end
  return dates
end

Just added 'i' which is incremented every iteration. Dates are only appended when i is even.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜