Hassan Chaudhry
Hassan Chaudhry

Reputation: 51

Getting nil error when adding elements in Array - Ruby

I am trying to get a number from the user, store this number in the array and then add everything in the array together to display a total.

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

But I am getting the error rb:10:in `+': nil can't be coerced into Integer (TypeError)

I guess its not allowing me to add whatever is in the array together. Anybody know a workaround for this?

Upvotes: 0

Views: 373

Answers (2)

Stefan
Stefan

Reputation: 114138

There are some issues with your code.

Array.new(20) – you probably think this creates an array of the given size. Well, it does, but it also fills the array with a default object of nil:

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

In Ruby, you just create an empty array. It will grow and shrink automatically. And instead of Array.new you can use an array literal:

names = []

for index in 0..5for loops are very unidiomatic. You should use one of these:

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

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

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

And finally:

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

You are pushing an element to the end of the array and then fetch it from the array using an absolute index. This only works if index and array size correlate exactly.

It's more robust to either use an explicit index for both, storing and fetching:

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

or to fetch the last element: (note that index isn't needed)

names.push data
x = x + names.last

Ruby also provides negative indices that are relative to the array's end:

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

Needless to say, you could just omit the fetching:

names.push data
x = x + data

It might be useful to separate the data gathering from the calculation:

numbers = []

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

and then:

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

Upvotes: 2

heringer
heringer

Reputation: 3188

You are initializing the array with 20 nil names. Then you push the first entered number to the array (position 21) and try to concat the position [0] (names[0]) that is nil.

Try to change the first line:

names = Array.new

Upvotes: 1

Related Questions