这将读取你的字典文件。我将内容存储在一个字符串中,然后 将它变成一个StringIO对象,让我假装它是一个文件。您可以使用 File.readlines
直接从文件本身的读取:
require 'pp'
require 'stringio'
text = 'AAB eel bbc
ABA did eye non pap mom ere bob nun eve pip gig dad nan ana gog aha
mum sis ada ava ewe pop tit gag tat bub pup
eke ele hah huh pep sos tot wow aba ala
bib dud tnt
ABB all see off too ill add lee ass err xii ann fee vii inn egg odd bee dee goo
woo cnn pee fcc tee wee ebb edd gee ott ree vee ell orr rcc att boo cee cii
coo kee moo mss soo doo faa hee icc iss itt kii loo mee nee nuu ogg opp pii
tll upp voo zee
'
file = StringIO.new(text)
dictionary = Hash[
file.readlines.slice_before(/^\S/).map{ |ary|
key, *values = ary.map(&:strip).join(' ').split(' ')
[key, values]
}
]
dictionary
是一个哈希看起来像:
{
"AAB"=>[
"eel", "bbc"
],
"ABA"=>[
"did", "eye", "non", "pap", "mom", "ere", "bob", "nun", "eve", "pip",
"gig", "dad", "nan", "ana", "gog", "aha", "mum", "sis", "ada", "ava",
"ewe", "pop", "tit", "gag", "tat", "bub", "pup", "eke", "ele", "hah",
"huh", "pep", "sos", "tot", "wow", "aba", "ala", "bib", "dud", "tnt"
],
"ABB"=>[
"all", "see", "off", "too", "ill", "add", "lee", "ass", "err", "xii",
"ann", "fee", "vii", "inn", "egg", "odd", "bee", "dee", "goo", "woo",
"cnn", "pee", "fcc", "tee", "wee", "ebb", "edd", "gee", "ott", "ree",
"vee", "ell", "orr", "rcc", "att", "boo", "cee", "cii", "coo", "kee",
"moo", "mss", "soo", "doo", "faa", "hee", "icc", "iss", "itt", "kii",
"loo", "mee", "nee", "nuu", "ogg", "opp", "pii", "tll", "upp", "voo", "zee"
]
}
您可以查找使用键:
dictionary['AAB']
=> ["eel", "bbc"]
而且在阵列内使用include?
进行搜索:
dictionary['AAB'].include?('eel')
=> true
dictionary['AAB'].include?('foo')
=> false