You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby数组问题:统计正数个数与负数求和代码报错排查

问题:统计正数个数与负数求和的Ruby代码报错排查

题目要求

给定一个整数数组。返回一个数组,其中第一个元素是正数的个数,第二个元素是负数的总和。0既不是正数也不是负数。如果输入是空数组或null,返回空数组。

我写的代码

def count_positives_sum_negatives(last)
   pos = []
   neg = []

   x = lst.each

    if x % 2 == 0
     pos.push x
     else neg.push x
    end
   y = pos.count
   z = neg.sum

 puts "[#{y},#{z}]"
end

测试用例

count_positives_sum_negatives([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15])
# 预期返回 [10, -65] 

报错信息

An error occurred while loading spec_helper.
Failure/Error: if (x % 2) == 0

NoMethodError:
  undefined method `%' for #<Enumerator: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]:each>
# ./lib/solution.rb:7:in `count_positives_sum_negatives'
# ./lib/solution.rb:18:in `<top (required)>'
# ./spec/spec_helper.rb:1:in `require'
# ./spec/spec_helper.rb:1:in `<top (required)>'
No examples found.
No examples found.

错误原因与修复方案

几个关键错误点

  1. 参数名不匹配:方法定义的参数是last,但代码里用的是lst,属于变量名拼写错误,后续会导致未定义变量问题。
  2. 枚举器误用:lst.each返回的是枚举器对象,不是数组里的单个元素,你对这个对象用%取余操作,自然会报“未定义该方法”的错误。
  3. 逻辑完全偏离需求:题目要求统计正数、计算负数总和,你却在判断元素是否为偶数,完全不符合要求。
  4. 返回值错误:题目要求返回数组,但你用puts打印结果,方法实际返回的是nil,不符合题目要求。
  5. 未处理边界情况:没有判断输入为空数组或nil的情况,不符合题目要求。

修复后的代码

def count_positives_sum_negatives(lst)
  # 处理空数组或nil的情况
  return [] if lst.nil? || lst.empty?

  pos_count = 0
  neg_sum = 0

  lst.each do |num|
    if num > 0
      pos_count += 1
    elsif num < 0
      neg_sum += num
    end
    # 0不做任何处理
  end

  # 返回要求的数组
  [pos_count, neg_sum]
end

代码说明

  • 先处理边界情况:输入为空或nil时直接返回空数组。
  • 用两个变量分别记录正数个数和负数总和,比用数组存储后再统计更高效。
  • 遍历数组每个元素,根据正负分别更新计数或总和。
  • 最后直接返回目标数组,满足题目要求的返回值类型。

内容的提问来源于stack exchange,提问作者R4V3N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:50:21