有人可以帮助解释为什么以下代码产生:
5.times do
star_count = star_count + 1
puts "*" * star_count
end
#=> NoMethodError: undefined method `+' for nil:NilClass
代码的预期效果如下图所示:
*
**
***
****
*****
很抱歉包含星号三角形作为代码...没有正确输出,所以这是我能想到的唯一解决方案。将三角形视为图像也不起作用。
答案 0 :(得分:2)
start_count
必须在循环之前初始化为0
。
无论如何,Ruby中有更多的惯用语:
5.times do |index|
puts '*' * (index + 1)
end
答案 1 :(得分:2)
您也可以使用upto
代替times
从另一个索引开始,而不是零。
1.upto(5) do |index|
puts '*' * index
end