简体   繁体   中英

How to push items to ruby array using loop

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?

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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