[英]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)
nil的未定义方法`split':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]. 它将分割一个像“321 123 432”这样的字符串并返回一个像[321,123,432]这样的数组。 Also the variable
size
is initialized again on each round. 此外,每轮都会再次初始化可变
size
。
Ignoring that, here's a more Ruby-like version: 忽略这一点,这是一个更像Ruby的版本:
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. 在Ruby中,你通常不会
for i in item_count ..
或者while i<item_count
使用类似for i in item_count ..
东西for i in item_count ..
因为我们有像.each这样的枚举器。
Obviously while i<lnth
not <=
: 显然,
while i<lnth
不是<=
:
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)
This should do it: 这应该这样做:
def nil.split *args
nil # splitting of nil, in any imaginable way, can only result again in nil
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.