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

Check your indentation. It will be 10 times easier to read with the right indentation (2 spaces). :)

Good use if .is_a? in add.

Why a second list of keywords? Why not just use @entries.keys?
#26 - Need to use @entries. I'm not sure what you are trying to accomplish with .assoc. The idea behind the results variable look correct. Try taking out the if statements and work with just the keywords.
#29 - check out String's .start_with? method. It will clean that up a little.

You'll need a keyword method in order to return things sorted.

Let me know if you need more help.

@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