-
-
Save ellismarte/02687f16f0565da6ad02 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tree | |
def initialize | |
@alphabet = ('a'..'z').to_a | |
@alphabet -= %w( p ) | |
create_first_children | |
end | |
def create_first_children | |
@alphabet.each do |character| | |
p character | |
self.class.send(:define_method, character.to_sym) { | |
return Node.new(:value => character) | |
} | |
end | |
end | |
def enter_new_word(word) | |
path = [] | |
characters = word.split("") | |
characters.each do |character| | |
if path.empty? | |
path << self.send(character) | |
elsif path[-1].respond_to?(character) | |
path << path[-1].send(character) | |
else | |
path << path[-1].create_new_child(character) | |
end | |
end | |
path[-1].word = word | |
end | |
def look_for_word(word) | |
path = [] | |
characters = word.split("") | |
characters.each do |character| | |
if path.empty? | |
path << self.send(character) | |
elsif path[-1].respond_to?(character) == false | |
break p 'word not found' | |
else | |
path << path[-1].send(character) | |
end | |
end | |
return path[-1].word | |
end | |
end | |
class Node | |
attr_accessor :value, :word | |
def initialize(params = {}) | |
@value = params[:value] | |
@word = nil | |
end | |
def create_new_child(character) | |
new_child = Node.new(:value => character) | |
self.class.send(:define_method, character) { return new_child } | |
end | |
end | |
dictionary = Tree.new | |
p 'the word hello does not exist in our dictionary' | |
dictionary.look_for_word('hello') | |
p 'we will now add hello to our dictionary' | |
dictionary.enter_new_word('hello') | |
# p 'we will now search for hello in our dictionary' | |
# dictionary.look_for_word('hello') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment