Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在读取文件时剪切行尾?_Ruby - Fatal编程技术网

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”]