[英]How do you loop through an input array and build an output array by pushing items on it using 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 控制台,我得到的只是列表中的日期。 如果我在控制器提高dates.inspect,我只得到2019年1月2日。
我怎样才能解决这个问题?
从您的编码风格来看,您似乎对 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
打印数组跨多行puts
。 如果要在一行中显示数组的内容,请改用p
。 不同之处在于puts
使用to_s
方法而p
使用inspect
方法。 传递给puts
数组将被展平并被视为多个参数。 每个论点都有自己的说法。
puts [1, 2]
# 1
# 2
#=> nil
p [1, 2]
# [1, 2]
#=> [1, 2]
用puts dates
puts "#{dates}"
替换puts dates
。 它将按预期打印数组,如 [01-02-2019, 01-03-2019, 01-04-2019]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.