我正在尝试追溯性地在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
答案 0 :(得分:1)
print
的返回值为nil
irb(main):001:0> a = print '1'
1=> nil
您应该在print
方法的最后一个语句中删除print
(或将return
替换为find
):
class Trie
...
def find(str)
node = @root
str.each_char do |ch|
return nil unless node = node[ch]
end
node[:end] && true
node[:end].to_a # <-------------- remove print
end
end
更改了测试用例(也用`word替换了"#{word}"
:
require 'test/unit'
class StringExtensionTest < Test::Unit::TestCase
...
def test_if_find_works
word = "ant"
t = Trie.new
t.build(word)
search = t.find('268')
ary = search.to_a
assert(ary.member? word)
end
end