Skip to content

Instantly share code, notes, and snippets.

@mneedham
Created November 27, 2011 22:43
Show Gist options
  • Select an option

  • Save mneedham/1398334 to your computer and use it in GitHub Desktop.

Select an option

Save mneedham/1398334 to your computer and use it in GitHub Desktop.
Incomplete implementation of a trie in ruby
class Trie
def initialize()
@trie = Hash.new()
end
def build(str)
chars = str.chars
chars.inject(@trie) do |prev, char|
unless prev[char]
prev[char] = Hash.new()
prev[char][:end] = true if chars.entries.last == char
end
prev[char]
end
end
def find(str)
str.chars.inject(@trie) do |prev, char|
return false unless prev[char]
prev[char]
end
true
end
def starts_with(str)
get_entries([], str.chars.inject(@trie) { |prev, char| prev[char] } , str)
end
private
def get_entries(entries, remaining, str)
remaining.each do |key, value|
entries << str if (key == :end)
if(value.is_a? Hash)
get_entries(entries, value, str + key)
end
end
entries.sort { |x, y| x.size <=> y.size }
end
end
f = Trie.new
f.build "mark"
f.build "markus"
f.build "malicious"
f.starts_with "mark"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment