2

I'm doing some word automation via ruby and am relatively inexperienced with it. I'm trying to functionise my code now and I am coming across this error

NameError: undefined local variable or method `doc' for main:Object
    from (irb):148:in `create_table'
    from (irb):152
    from C:/Ruby192/bin/irb:12:in `<main>'

Which I'm getting from this sample code i knocked up

#Get the correct packages
require 'win32ole'

#setting up the Word
word = WIN32OLE.new('Word.Application')
#Shows the word Application
word.Visible = true
#Setting doc to the active document
doc = word.Documents.Add
doc = word.ActiveDocument

def create_table
  doc.Tables.Add(word.Selection.Range, 4, 2) #Creates a table with 3 rows and 2 columns
  doc.Tables(1).Borders.Enable = true
end

create_table
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Cam B
  • 195
  • 2
  • 3
  • 12
  • If you had remembered to indent your code, your forgetting to pass `doc` as a parameter would have been more obvious. – Andrew Grimm Dec 09 '10 at 22:22

1 Answers1

4

Your problem is that inside your create_table method, you were referencing variables that you have in the main scope but didn't pass to the method. This works for what you want:

require 'win32ole'

#setting up the Word
word = WIN32OLE.new('Word.Application')
#Shows the word Application
word.Visible = true
#Setting doc to the active document
doc = word.Documents.Add
doc = word.ActiveDocument

def create_table(d, w)
  d.Tables.Add(w.Selection.Range, 4, 2)
  d.Tables(1).Borders.Enable = true
end

create_table(doc, word)

Notice that it now passes the references for doc and word into the function. Also, by the way, you are creating a table with 4 rows and 2 columns.

Paul Hoffer
  • 12,606
  • 6
  • 28
  • 37
  • Cheers for that, I've only been dealing with R so far in my programming journeys, so I'm fairly ignorant about how things work in ruby. Also yeah I need to update my comments in my original code, it was just a chunk of code i copied out of my main script which has been edited since. – Cam B Dec 09 '10 at 23:19