Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method `split' for nil:NilClass (NoMethodError) for an array

Tags:

file-io

ruby

I am trying to read a file which contains some numbers. And then i want to convert them into integer. When i'm trying like below, it is ok.

input = IO.readlines(filename)
size = input[0].split(/\s/).map(&:to_i)

But, when i'm trying like below, it gives me that error.

input = IO.readlines(filename)
lnth = input.length
i=0
while i<=lnth
  size = input[i].split(/\s/).map(&:to_i)
  i=i+1
end

undefined method `split' for nil:NilClass (NoMethodError)

How I solve the error now?

like image 740
Muktadir Avatar asked Oct 01 '22 18:10

Muktadir


1 Answers

Obviously while i<lnth not <=:

while i<lnth
  size = input[i].split(/\s/).map(&:to_i)
  i=i+1
end

but preferably use:

size = line.split(/\s/).map(&:to_i)
like image 108
zishe Avatar answered Oct 04 '22 21:10

zishe