trie icon indicating copy to clipboard operation
trie copied to clipboard

Add convenience method to build trie from Enumerable

Open roryokane opened this issue 10 years ago • 1 comments

It could be called something like Trie.from_enumerable. Its definition is simple:

def Trie.from_enumerable(enumerable)
  enumerable.reduce(Trie.new) do |trie, item|
    trie.add(item); trie
  end
end

I would use this in my program to easily build a Trie from a text file:

words_trie = File.open(WORDLIST_FILE_PATH, 'r') do |wordlist_file|
  Trie.from_enumerable(wordlist_file.each_line)
end

If you want, you could also provide a version that adds both keys and values:

def Trie.from_key_value_enumerable(kv_enumerable)
  trie = Trie.new
  kv_enumerable.each do |key, value|
    trie.add(key, value)
  end
  trie
end

roryokane avatar Apr 05 '15 18:04 roryokane

Love it. Patches accepted. :D

tyler avatar Apr 05 '15 22:04 tyler