Muktadir
Muktadir

Reputation: 303

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

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?

Upvotes: 6

Views: 26747

Answers (4)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

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)

Upvotes: 2

YasirAzgar
YasirAzgar

Reputation: 1451

Convert it to string before splitting, i.e input[i].to_s.split(/\s/)

may be input[i] is nil, so convert it to string

ref

Upvotes: 0

Boris Stitnicky
Boris Stitnicky

Reputation: 12588

This should do it:

def nil.split *args
  nil # splitting of nil, in any imaginable way, can only result again in nil
end

Upvotes: 0

Kimmo Lehto
Kimmo Lehto

Reputation: 6041

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.

Upvotes: 2

Related Questions