2

我正在通过 ruby​​ 进行一些单词自动化,并且相对缺乏经验。我现在正在尝试使我的代码功能化,但遇到了这个错误

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>'

我从这个示例代码中得到的,我敲了

#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
4

1 回答 1

4

您的问题是,在您的create_table方法中,您引用了在主范围内但未传递给方法的变量。这适用于您想要的:

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)

请注意,它现在将引用传递docword函数中。另外,顺便说一下,您正在创建一个有 4 行和 2 列的表。

于 2010-12-09T18:26:22.553 回答