Matt Elhotiby
Matt Elhotiby

Reputation: 44066

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

Upvotes: 0

Views: 174

Answers (2)

rubyprince
rubyprince

Reputation: 17803

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.

Upvotes: 1

Mark
Mark

Reputation: 461

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.

Upvotes: 1

Related Questions