[英]Undefined method `%' for nil:NilClass (NoMethodError) Ruby on Rails
Getting an undefined method error for '%' for nil:NilClass (NoMethodError)为 nil:NilClass (NoMethodError) 获取 '%' 的未定义方法错误
Here's the simple function I have:这是我拥有的简单 function:
def oddball_sum(numbers)
i =0
arr = []
while i <= numbers.length
if numbers[i] % 2 != 0
arr << numbers[i]
end
i +=1
end
return arr.sum
end
Can't determine the issue;无法确定问题; the method is supposed to take an array of integers and return the sum of all the odd elements.该方法应该采用整数数组并返回所有奇数元素的总和。
Suppose that numbers is [1,2,3,4], when i increase to 4, numbers[4] will return nil假设numbers是[1,2,3,4],当我增加到4时,numbers[4]会返回nil
The condition should be i < numbers.length
条件应该是i < numbers.length
Instead of using while
, you can also use inject
除了使用while
,您还可以使用inject
numbers.inject(0) { |sum, i| i % 2?= 0: sum + i : sum }
You can go through arrays on the ruby docs ruby is one of the elegantly written languages.您可以在 ruby 文档中 go到 arrays 文档ruby 是优雅的书面语言之一。 less code to achieve the same result.更少的代码来实现相同的结果。 As follow the solution this would do按照解决方案这样做
numbers.select {|num| num.odd? }.sum
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.