1

为什么我的foo()函数打印出长度为 5 的字符串“YAAR”?

def foo() 
map = Hash.new
File.open('dictionary.txt').each_line{ |s|
    word = s.split(',')
    if word.any? { |b| b.include?('AA') }
        puts word.last
        puts word.last.length
    end
    }
end

一些文件.txt

265651,YAAR
265654,YAARS

输出

YAAR
5
YAARS
6
4

2 回答 2

3

你在两个字符串的末尾都有一个换行符 '\n' 。因此,您的拆分正在接收:

"265651,YAAR\n"
"265654","YAARS\n"
于 2013-02-28T01:07:42.460 回答
3

从文件中读取,您将在所有行的末尾获得一个新行字符 (\n)(可能最后一行除外)

代替

word = s.split(',')

在你的循环中,使用这个

word = s.split(',').map { |s| s.chomp }
于 2013-02-28T01:13:01.177 回答