1

I am trying to create an array of dates using loop. But the loop is only pushing one date and when I query an array I see it's not an array, rather a list. Help.

date1 = '01-01-2019'.to_date
dates = []
count = 0
repeat = 3

while (count < repeat)
 count += 1
 date2 = date1 + count.month
 dates << date2
 puts dates
end

Expected results should be [01-02-2019, 01-03-2019, 01-04-2019].

However, if I use rails console, all I get are the dates in a list. If I raise dates.inspect in controller, I only get 01-02-2019.

How can I fix this?

9
  • 2
    FYI: terms list and array in Ruby are the exact synonyms. Commented Jan 6, 2019 at 16:46
  • 2
    dates = 3.times.map { |i| '01-01-2019'.to_date + i.months } does what you assumingly need. Commented Jan 6, 2019 at 16:48
  • 1
    I tested your piece of code and it's working fine. [Fri, 01 Feb 2019, Fri, 01 Mar 2019, Mon, 01 Apr 2019]. Check if the moment you are formatting the result is okay. Commented Jan 6, 2019 at 17:26
  • 1
    @Tiw, a small thing, but I think it's clearer to change map's receiver to, say, (1..repeat) or 1.upto(repeat). Commented Jan 6, 2019 at 18:45
  • 1
    Here's a hint: in Ruby, the answer to every question of the form "How do I X using loops" is "You don't, use Enumerable methods instead". If you ever find yourself writing a loop in Ruby, there's a 99.999% chance you are doing something wrong. Commented Jan 6, 2019 at 20:09

2 Answers 2

1

From your coding style it seems you're pretty new to Ruby. A more Ruby-like approach would be:

start_date = '01-01-2019'.to_date
repeat     = 3

dates = 1.upto(repeat).map { |count| start_date + count.months }
# or
dates = (1..repeat).map { |count| start_date + count.months }

Then to print the dates array use:

puts dates

As far as I can tell, your provided code should work. Keep in mind that puts prints arrays across multiple lines. If you want to display the contents of the array on a single line use p instead. The difference is that puts uses the to_s method while p uses the inspect method. Arrays passed to puts will be flattened and seen as multiple arguments instead. Every argument will get its own line.

puts [1, 2]
# 1
# 2
#=> nil

p [1, 2]
# [1, 2]
#=> [1, 2]
Sign up to request clarification or add additional context in comments.

Comments

0

Replace puts dates by puts "#{dates}". It will print array as expected like [01-02-2019, 01-03-2019, 01-04-2019].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.