So I have this ruby code I grabbed from wikipedia and I modified a bit:
@trie = Hash.new()
def build(str)
node = @trie
str.each_char { |ch|
cur = ch
prev_node = node
node = node[cur]
if node == nil
prev_node[cur] = Hash.new()
node = prev_node[cur]
end
}
end
build('dogs')
puts @trie.inspect
I first ran this on console irb, and each time I output node
, it just keeps giving me an empty hash each time {}
, but when I actually invoke that function build with parameter 'dogs'
string, it actually does work, and outputs {"d"=>{"o"=>{"g"=>{"s"=>{}}}}}
, which is totally correct.
This is probably more of a Ruby question than the actual question about how the algorithm works. I don't really have adequate Ruby knowledge to decipher what is going on there I guess.
prev_node[cur] = Hash.new
, and consider whatprev_node[cur]
is--but remember thatprev_node
itself is a hash with a character key, that happens to point to an empty hash (for one iteration). – Farwell