0

我正在尝试追溯性地在 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
4

1 回答 1

1

print的返回值为nil

irb(main):001:0> a = print '1'
1=> nil

您应该在方法的最后一个语句中删除print(或替换print为) :returnfind

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
于 2013-09-11T16:49:48.077 回答