有没有办法在Ruby中动态创建数组?例如,假设我想循环浏览一系列书籍作为用户的输入:
books = gets.chomp
用户输入:
"The Great Gatsby, Crime and Punishment, Dracula, Fahrenheit 451,
Pride and Prejudice, Sense and Sensibility, Slaughterhouse-Five,
The Adventures of Huckleberry Finn"
Run Code Online (Sandbox Code Playgroud)
我把它变成一个数组:
books_array = books.split(", ")
Run Code Online (Sandbox Code Playgroud)
现在,对于每本书的用户输入,我想用Ruby来创建一个数组.伪代码来做到这一点:
x = 0
books_array.count.times do
x += 1
puts "Please input weekly sales of #{books_array[x]} separated by a comma."
weekly_sales = gets.chomp.split(",")
end
Run Code Online (Sandbox Code Playgroud)
显然这不起作用.它会weekly_sales一遍又一遍地重新定义.有没有办法实现我所追求的,并且.times方法的每个循环都创建一个新数组?
weekly_sales = {}
puts 'Please enter a list of books'
book_list = gets.chomp
books = book_list.split(',')
books.each do |book|
puts "Please input weekly sales of #{book} separated by a comma."
weekly_sales[book] = gets.chomp.split(',')
end
Run Code Online (Sandbox Code Playgroud)
在ruby中,有一个哈希的概念,它是一个键/值对.在这种情况下,weekly_sales是哈希,我们使用书名作为键,数组作为值.
我对你的代码做了一个小小的改动,而不是使用books.count.times定义循环,然后用计数器取消引用数组元素,每个都是迭代集合的更好方法.