简体   繁体   English

nil 的未定义方法“%”:NilClass (NoMethodError) Ruby on Rails

[英]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.

相关问题 Ruby on Rails NoMethodError:nil:NilClass的未定义方法“ []” - Ruby on Rails NoMethodError: undefined method `[]' for nil:NilClass nil:NilClass Ruby on Rails的未定义方法&#39;&gt;&#39;(NoMethodError) - undefined method `>' for nil:NilClass Ruby on Rails (NoMethodError) Ruby On Rails - NoMethodError:nil:NilClass 的未定义方法“[]” - Ruby On Rails - NoMethodError: undefined method `[]' for nil:NilClass Rails 5.2 上的 Ruby - NoMethodError(nil:NilClass 的未定义方法“主机”): - Ruby on Rails 5.2 - NoMethodError (undefined method `host' for nil:NilClass): 了解Ruby on Rails:NoMethodError(nil:NilClass的未定义方法“ []”): - Learn Ruby on Rails: NoMethodError (undefined method `[]' for nil:NilClass): Ruby on Rails 如何修复 NoMethodError: undefined method `id' for nil:NilClass - Ruby on Rails how to fix NoMethodError: undefined method `id' for nil:NilClass Ruby - NoMethodError(nil的未定义方法:NilClass): - Ruby - NoMethodError (undefined method for nil:NilClass): Ruby:NoMethodError:nil的未定义方法`&lt;&lt;&#39;:NilClass - Ruby: NoMethodError: undefined method `<<' for nil:NilClass undefined方法[]为nil:ruby中的NilClass(NoMethodError)...为什么? - undefined method [] for nil:NilClass (NoMethodError) in ruby… Why? 未定义的方法“ +”,用于nil:NilClass(NoMethodError)-Ruby - undefined method `+' for nil:NilClass (NoMethodError) - Ruby
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM