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

I am trying to read a file containing some numbers. And then I want to convert them into a whole. When I try, as shown below, this is normal.

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

But, when I try, as shown below, it gives me this 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 `split 'method for nil: NilClass (NoMethodError)

How do I solve the error now?

+4
source share
4 answers

Obviously while i<lnthnot <=:

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

but it is preferable to use:

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

I wonder what this should do?

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

"321 123 432" [321, 123, 432]. size .

, Ruby- :

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

Ruby for i in item_count .. while i<item_count, .each.

+2

, .. input[i].to_s.split(/\s/)

input[i] is nil,

ref

0

:

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

Source: https://habr.com/ru/post/1541245/


All Articles