Class: Dictionary::AnagramExtractor

Inherits:
Object
  • Object
show all
Includes:
AnagramExtractorC
Defined in:
lib/dictionary/anagram_extractor.rb

Overview

The class AnagramExtactor, contains the implementation to get all the anagrams from a dictionary provided text file.

Examples:

Example Usage

extractor = AnagramExtractor.new('my_dictionary.txt')
extractor.extract!
extractor.export('anagrams.txt')

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file = nil) ⇒ AnagramExtractor

An AnagramExtactor instance should be initialized with the location of the file to scan.

Parameters:

  • file (String, Pathname) (defaults to: nil)

    the location of the file.

Raises:



21
22
23
# File 'lib/dictionary/anagram_extractor.rb', line 21

def initialize(file=nil)
  self.file = file if file
end

Instance Attribute Details

#anagramsObject (readonly)

Holds the anagrams extracted.



15
16
17
# File 'lib/dictionary/anagram_extractor.rb', line 15

def anagrams
  @anagrams
end

#fileObject

Holds the dictionary file.



13
14
15
# File 'lib/dictionary/anagram_extractor.rb', line 13

def file
  @file
end

Instance Method Details

#export(location) ⇒ String

Saves the anagram dictionary to a provided file.

Parameters:

  • location (String, Pathname)

    the location of the file to write.

Returns:

  • (String)

    the full path to the exported file.

Raises:



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/dictionary/anagram_extractor.rb', line 57

def export(location)
  location    = get_full_location location
  @anagrams ||= []

  raise Dictionary::Error::FileAlreadyExistsError if File.exists? location
  unless File.directory? File.dirname(location)
    raise Dictionary::Error::PathNotFoundError
  end
  File.open(location, 'w') { |file| file.puts @anagrams.join("\n") }
  location
end

#extract!(in_c = false) ⇒ Array?

Extracts the anagrams from the provided file.

Parameters:

  • in_c (true, false) (defaults to: false)

    Execute the code in C.

Returns:

  • (Array, nil)

    the anagram list, or nil if no dictionary.



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dictionary/anagram_extractor.rb', line 39

def extract!(in_c=false)
  return unless @file
  reset_dictionaries
  File.read(@file).each_line do |word|
    word = word.strip
    has_an_anagram = anagram_for? word, in_c
    @anagrams += [word, has_an_anagram] if has_an_anagram
    @dictionary << word
  end
  @anagrams = @anagrams.uniq
end