Created
September 15, 2012 00:37
-
-
Save colemanfoley/3725822 to your computer and use it in GitHub Desktop.
Dictionary class
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 Dictionary | |
attr_accessor :entries | |
attr_accessor :keywords | |
def initialize | |
@entries = Hash.new | |
end | |
def add(entry) | |
if entry.is_a? Hash | |
@entries.merge!(entry) | |
elsif entry.is_a? String | |
temporary_hash = {entry => nil} | |
entry = temporary_hash | |
@entries.merge!(entry) | |
end | |
end | |
def include?(word) | |
return @entries.keys.include?(word) | |
end | |
def find(query) | |
results = Hash.new | |
@entries.each do |entry| | |
if entry.keys[0].start_with?(query) | |
results.merge!(entry) | |
end | |
end | |
return results | |
end | |
def keywords | |
return @entries.keys.sort | |
end | |
def empty? | |
return @entries.empty? | |
end | |
end |
Ah, I missed the part about the keywords method the first time I read your comment. So I need to have a keywords method, not a keywords array. Got it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote it in SublimeText using two spaces for a tab. The indentation always gets messed up when I paste it into Gist.
Regarding the @Keywords array, yeah, I'll just take that out.
With assoc, I was just trying to check if the string existed in the dictionary first, so I could skip looping through the array if the string was nowhere in the array to start with. But I guess that isn't any more efficient because the assoc requires going through the whole array anyway, and it will require checking through the array twice if the string is in the array. So I'll take that out.
Start-with sounds like it'll be very handy. Thanks.