2014-06-27 60 views
0

代码:红宝石each_line比较只返回最后一个字符串

class Comparer 

words = "asdf-asdf-e-e-a-dsf-bvc-onetwothreefourfive-bob-john" 
foundWords = [] 

File.foreach('words.txt') do |line| 
    substr = "#{line}" 
    if words.include? substr 
     puts "Found " + substr 
     foundWords << substr    
    end 
end 

wordList = foundWords.join("\n").to_s    
puts "Words found: " + wordList 

end 

words.txt:

one 
blah-blah-blah 
123-5342-123123 
onetwo 
onetwothree 
onetwothreefour 

我想代码返回的包括?不过当代码运行的所有实例,wordList只包含words.txt的最后一行(“onetwothreefour”)。为什么words.txt中的其他行不会被分解?

回答

3

由于您期望找到所有其他行,因此它们在末尾具有“隐藏的”换行符。你可以看看自己。

File.foreach('words.txt') do |line| 
    puts line.inspect 
    # or 
    p line 
end 

您可以通过使用chomp!方法上line摆脱换行符。

File.foreach('words.txt') do |line| 
    line.chomp! 

    # proceed with your logic 
end 
+0

谢谢塞尔吉奥的快速和正确的答案! – user3782426