【问题标题】:Getting nil error when adding elements in Array - Ruby在数组中添加元素时出现零错误 - Ruby
【发布时间】:2021-02-17 01:59:05
【问题描述】:

我正在尝试从用户那里获取一个数字,将此数字存储在数组中,然后将数组中的所有内容相加以显示总数。

names = Array.new(20)
sum = 0

x = 0

for index in 0..5
  puts "Enter a number: "
  data = gets.to_i
  names.push data
  x = x + names[index]
end

puts x

但我收到了错误rb:10:in `+': nil can't be coerced into Integer (TypeError)

我猜它不允许我将数组中的任何内容添加在一起。有人知道解决方法吗?

【问题讨论】:

  • x = x + data - 无需再次从数组中获取元素。
  • 是的,我知道,我只是想了解数组,所以我试图从数组中获取值

标签: arrays ruby


【解决方案1】:

您的代码存在一些问题。

Array.new(20) - 你可能认为这会创建一个给定大小的数组。嗯,确实如此,但它也用nil 的默认对象填充数组:

Array.new(3)
#=> [nil, nil, nil]

在 Ruby 中,您只需创建一个空数组。它会自动增长和收缩。而不是Array.new,您可以使用array literal

names = []

for index in 0..5for 循环非常单一。您应该使用以下之一:

(0..5).each do |index|
  # ...
end

0.upto(5) do |index|
  # ...
end

6.times do |index|
  # ...
end

最后:

names.push data
x = x + names[index]

您正在将一个元素推送到数组的末尾,然后使用绝对索引从数组中获取它。这仅在 index 和数组大小完全相关时才有效。

对存储和获取都使用显式索引更加健壮:

names[index] = data
x = x + names[index]

或获取last 元素:(请注意,不需要index

names.push data
x = x + names.last

Ruby 还提供了相对于数组末尾的负索引:

names.push data
x = x + names[-1]

不用说,你可以省略获取:

names.push data
x = x + data

将数据收集与计算分开可能会很有用:

numbers = []

6.times do
  puts 'Enter a number: '
  numbers << gets.to_i
end

然后:

numbers = [1, 2, 3, 4, 5, 6] # <- example input

numbers.sum
#=> 21

# -- or --

numbers.inject(:+)
#=> 21

# -- or --

sum = 0
numbers.each { |n| sum += n }
sum
#=> 21

【讨论】:

  • 天哪,非常感谢,Ruby 的工作方式显然与 Java 大不相同。我对 Java 很熟悉,所以我利用我从那里学到的知识在 Ruby 中编写代码,但显然学习曲线要​​大得多
【解决方案2】:

您正在使用 20 个 nil 名称初始化数组。然后将第一个输入的数字推送到数组(位置 21)并尝试连接为 nil 的位置 [0](名称 [0])。

尝试更改第一行:

names = Array.new

【讨论】:

  • 争论是多余的,你可以直接写names = Array.new或者干脆names = []
  • 按照 Stefan 的建议编辑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 2015-02-05
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多