简体   繁体   中英

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?

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.

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)

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

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

ref

This should do it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM