我无法总结一个数组。这是我现有的代码:
pageArray = Array.new
puts "How many pages long is the book you're reading?"
pageArray << gets.chomp
puts "Are you reading any other books right now?"
yn = gets.chomp
while yn != "no" do
puts "How many pages long is your next book?"
pageArray << gets.chomp
puts "Are you reading any other books right now?"
yn = gets.chomp
end
pageSum = pageArray.reduce(:+)
puts pageSum
当我通过并输入值100和50时,最终的回报是“10050”,而不是“150”。我错过了一些明显的东西吗
答案 0 :(得分:1)
代码可以写得更清楚,更像Ruby。这是一些更惯用的未经测试的代码:
page_array = []
puts "How many pages long is the book you're reading?"
page_array << gets.chomp
loop do
puts 'Are you reading any other books right now?'
yn = gets.chomp.downcase
break if yn == 'no'
puts 'How many pages long is your next book?'
page_array << gets.chomp.to_i
end
page_sum = page_array.reduce(:+)
puts page_sum
注意:
loop do
将永远循环。当您收到休息值时,只需break
。答案 1 :(得分:0)
您正在输入字符串并将它们连接起来。
使用gets.chomp.to_i
答案 2 :(得分:0)
您需要将从gets
获得的字符串更改为int。
pageArray << gets.chomp.to_i