简体   繁体   English

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

[英]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] .预期结果应为[01-02-2019, 01-03-2019, 01-04-2019]

However, if I use rails console, all I get are the dates in a list.但是,如果我使用 rails 控制台,我得到的只是列表中的日期。 If I raise dates.inspect in controller, I only get 01-02-2019 .如果我在控制器提高dates.inspect,我只得到2019年1月2日

How can I fix this?我怎样才能解决这个问题?

From your coding style it seems you're pretty new to Ruby.从您的编码风格来看,您似乎对 Ruby 还很陌生。 A more Ruby-like approach would be:更像 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 }

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.请记住, puts打印数组跨多行puts If you want to display the contents of the array on a single line use p instead.如果要在一行中显示数组的内容,请改用p The difference is that puts uses the to_s method while p uses the inspect method.不同之处在于puts使用to_s方法而p使用inspect方法。 Arrays passed to puts will be flattened and seen as multiple arguments instead.传递给puts数组将被展平并被视为多个参数。 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}" .puts dates puts "#{dates}"替换puts dates It will print array as expected like [01-02-2019, 01-03-2019, 01-04-2019].它将按预期打印数组,如 [01-02-2019, 01-03-2019, 01-04-2019]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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