這將讀取你的字典文件。我將內容存儲在一個字符串中,然後 將它變成一個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