如何使用循环将项目推送到 ruby 数组

How to push items to ruby array using loop

我正在尝试使用循环创建一个日期数组。但是循环只推送一个日期,当我查询一个数组时,我发现它不是一个数组,而是一个列表。帮助。

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

预期结果应为 [01-02-2019, 01-03-2019, 01-04-2019].

但是,如果我使用 rails 控制台,我得到的只是列表中的日期。如果我在控制器中 raise dates.inspect,我只会得到 01-02-2019

我该如何解决这个问题?

从您的编码风格来看,您似乎对 Ruby 很陌生。更像 Ruby 的方法是:

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 }

然后打印日期数组使用:

puts dates

据我所知,您提供的代码应该可以工作。请记住 puts prints arrays across multiple lines. If you want to display the contents of the array on a single line use p 代替。区别在于puts使用to_s方法,而p使用inspect方法。传递给 puts 的数组将被展平并被视为多个参数。每个参数都有自己的一行。

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

p [1, 2]
# [1, 2]
#=> [1, 2]

puts dates 替换为 puts "#{dates}"。 它将按预期打印数组,如 [01-02-2019、01-03-2019、01-04-2019]。