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