Ruby 如何在读取文件时剪切行尾?
我正在将文件的内容读入数组。行中的最后一项是带行尾字符,这是我不想要的。以下是我正在做的:Ruby 如何在读取文件时剪切行尾?,ruby,Ruby,我正在将文件的内容读入数组。行中的最后一项是带行尾字符,这是我不想要的。以下是我正在做的: @arr = [] File.open('somefile.txt', 'r') do |file| while (line = file.gets) puts "'#{line.split('|')[2]}'" @arr << line end end 对于col3,它包括行尾字符。我可以从上面的puts中看出这一点,它输出: 'col3
@arr = []
File.open('somefile.txt', 'r') do |file|
while (line = file.gets)
puts "'#{line.split('|')[2]}'"
@arr << line
end
end
对于col3
,它包括行尾字符。我可以从上面的puts
中看出这一点,它输出:
'col3" 我尝试了file.get.chomp,但这会引发以下错误: nil:NilClass(NoMethodError)的未定义方法“chomp”
如何删除行尾字符?您的代码失败,因为当文件被完全读取时,
file.get
返回nil
,调用.chomp
,就会抛出您提到的错误
但是,您可以在while
块内调用.chomp()
,其中可以保证行
不是nil
例如,代替
puts "'#{line.split('|')[2]}'"
你可以
puts "'#{line.chomp.split('|')[2]}'"
您的代码失败,因为当文件被完全读取时,
file.get
返回nil
,调用.chomp
,就会抛出您提到的错误
但是,您可以在while
块内调用.chomp()
,其中可以保证行
不是nil
例如,代替
puts "'#{line.split('|')[2]}'"
你可以
puts "'#{line.chomp.split('|')[2]}'"
尝试:如果(line.size>0){puts“{line.split(“{124;”)[2]}'@arr我建议你写
@arr=[];File.foreach('animals.txt'){line{arr[“col1 | col2 | col3”,“col1 | col2 | col3”,“col1 | col2 | col2 | col3”][/code>。尝试:如果(line.size>0{puts”{col1 | col2}col2}建议你写('animals.txt'){| line |@arr[“col1 | col2 | col3”,“col1 | col2 | col3”,“col1 | col2 | col3”]
。