![](/img/trans.png)
[英]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.