Mar 04

Ever wanted to have a spell check function in your Ruby Program? As long as you have MS Word installed, you can use the Spellcheck function from your program. Here’s the code:

require 'exo/iswindows'

if not RUBY_PLATFORM.isWindows?
   puts "This program only runs under Windows!"

require 'win32ole'

def spellcheck(scstring)
   word ='Word.Application')
   doc = word.Documents.Add     ## Blank document

   word.Selection.Text = scstring

   ### return the corrected text
   if not scstring[/ /]      ## only one word with no spaces in the string
     # highlight the word first,
     word.Selection.MoveLeft( 'Unit'=>2,
            'Count'=> 1,
   ## multiple words end up already selected after the spell check
   # then retrieve.
   correct = word.Selection.Text
   return correct

if __FILE__ == $0
   puts "Corrected => #{spellcheck(ARGV[0])}"

The program opens a new document, pastes the text to check into the document, and then brings up the spellcheck dialog box with any words it can’t find in the dictionary and prompts you to correct the mistakes. Here’s an sample output:

C:\Server6\Dev\Ruby>ruby spellcheck.rb "this is a test srting to seee how the slpell check is working"
Corrected => This is a test string to see how the spell check is working

C:\Server6\Dev\Ruby>ruby spellcheck.rb  antidisestablishmenttarianism
Corrected => antidisestablishmentarianism

For some reason, if you check multiple words, the dialog auto-closes after the last ‘fix’ …but if its just one word, it stays open until you click the close button. Conversely, multiple words stay selected in the Word doc after the dialog closes, but with only one word, it does not stay selected, and you have to select it back in order to read it off the page of the document.

SociBook Digg Facebook Google Yahoo Buzz StumbleUpon
Tagged with: