我正在尝试追溯性地在 Trie 上构建测试。trie 实际上可以工作并返回存储的单词,但是当我尝试对哈希运行测试时,它告诉我 Trie 正在生成一个 nilclass。
这是 t9_trie.rb(经过调整以反映 falsetru 的 v 有用修复)
class Trie
def initialize
@root = Hash.new
end
def build(word)
node = @root
t9num = word.tr('a-z', '22233344455566677778889999')
t9num.each_char do |ch|
node[ch] ||= Hash.new
node = node[ch]
end
(node[:end] ||= []) << word
end
def find(str)
node = @root
str.each_char do |ch|
return nil unless node = node[ch]
end
node[:end] && true
node[:end].to_a
end
end
# words = %w[ant bear cat anu amulet quest question whatchamacalit yes zest]
# words = File.open('dictionary_copy.txt') {|f| f.read }.split
word = "ant"
t = Trie.new
t.build("#{word}")
puts t.inspect
puts t.find('268').class
search = [t.find('268')]
ary = search.to_a
puts ary.class
puts ary
这是 t9_trie_spec.rb,现在可以使用:
require 'test/unit'
here = File.expand_path(File.dirname(__FILE__))
require "#{here}/sandbox"
class StringExtensionTest < Test::Unit::TestCase
def test_if_Trie_exists
word = "ant"
t = Trie.new
t.build("#{word}")
assert_match /Trie/, t.to_s, "no Trie found"
end
def test_if_find_works
word = "ant"
t = Trie.new
t.build(word)
search = t.find('268') #had to remove extra nested arrays
assert_send([search, :member?, word]) #and tweak this language
end
end