Skip to content

Instantly share code, notes, and snippets.

@colemanfoley
Created September 15, 2012 00:37
Show Gist options
  • Save colemanfoley/3725822 to your computer and use it in GitHub Desktop.
Save colemanfoley/3725822 to your computer and use it in GitHub Desktop.
Dictionary class
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
@ryanjm
Copy link

ryanjm commented Sep 25, 2012

  • I realized that you are probably just using tab within Workshop... that is fine. :)

@colemanfoley
Copy link
Author

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.

@colemanfoley
Copy link
Author

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