Tom Aldy
Tom Aldy

Reputation: 15

Range loop printing out the range?

When I am trying to loop through the days of the week, the output seems to simply be the start date and end date of the range, rather than the name of the day I am trying to print out.

I am doing it this way as there are more pieces of content I want to print out per day. Here's what I have in my model:

(Date.today.beginning_of_week..Date.today.end_of_week).each do |day|
    day.strftime("%A")
end

I have no idea why all I am getting in the view is this:

2015-10-05..2015-10-11

If someone could shed some light on this, I'd really appreciate it.

Upvotes: 1

Views: 239

Answers (2)

zetetic
zetetic

Reputation: 47548

You are expecting it to return an array, but it's just returning the original Range object:

(Date.today.beginning_of_week..Date.today.end_of_week)

because it is being called with :each. You could use :map instead:

(Date.today.beginning_of_week..Date.today.end_of_week).map {|date| date}

but if you don't need to transform the dates while enumerating them, you can simply use :to_a:

(Date.today.beginning_of_week..Date.today.end_of_week).to_a

Upvotes: 2

sawa
sawa

Reputation: 168091

I don't know how you are printing the result, but if you have puts on the entire code you cited, then it will print the receiver of each (range of dates; what you have now). If you want to print what you have inside the block, then put puts inside the block.

(Date.today.beginning_of_week..Date.today.end_of_week).each do |day|
  puts day.strftime("%A")
end

Upvotes: 0

Related Questions