Skip to content

Instantly share code, notes, and snippets.

@sirupsen
Last active April 5, 2019 16:28
Show Gist options
  • Save sirupsen/6479740 to your computer and use it in GitHub Desktop.
Save sirupsen/6479740 to your computer and use it in GitHub Desktop.
Implementation of a trie in Ruby.
class Trie
attr_accessor :word, :trie
def initialize
@trie = {}
@word = false
end
def <<(string)
node = string.each_char.inject(self) { |node, char| node.trie[char] ||= Trie.new }
node.word = true
end
def detect(string)
node = string.each_char.inject(self) { |node, char|
return false unless node.trie[char]
node = node.trie[char]
}
node.word
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment