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

21,429

Solution 1

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)

Solution 2

I wonder what this is supposed to do?

size = line.split(/\s/).map(&:to_i)

It will split a string like "321 123 432" and return an array like [321, 123, 432]. Also the variable size is initialized again on each round.

Ignoring that, here's a more Ruby-like version:

File.readlines(filename).each do |line|
  size = line.split(/\s/).map(&:to_i)
end

In Ruby you don't usually use anything like for i in item_count .. or while i<item_count since we have the Enumerators like .each.

Share:
21,429
Muktadir
Author by

Muktadir

Updated on August 22, 2020

Comments

  • Muktadir
    Muktadir over 3 years

    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?