我一直在使用Caracal gem用于Ruby,我很难让它在方法之间跳转,同时仍然写入同一个文档。例如:
def main_method
Caracal::Document.save "test.docx" do |docx|
docx.p "stuff"
docx.h1 "more stuff"
docx.h2 "even more stuff"
if $var == 1
method1
else
method2
end
end
end
def method1
docx.p "write this"
end
def method2
docx.p "or write this instead"
end
但是不,如果我跳到另一个方法,它不会继续写在文档中,显然没有办法让Caracal打开文档,最后定位,继续写(如Rubý的File.open) ('test.txt','a')
有人知道这个方法吗?我知道我可以把“写这个”直接放在if语句中,但这只是一个基本的例子,实际上我需要几个分支,因为满足不同的条件,所以我真的需要跳到不同的方法,或者它会是一个可怕的混乱。
谢谢社区!!
答案 0 :(得分:1)
The variable docx
is only in scope within the block attached to the save
method. In order for the other methods to be able to see and use this variable you will need to pass it as a parameter.
First make the methods accept a parameter, e.g.
def method1(docx)
docx.p "write this"
end
then pass the actual variable as an argument when calling the method:
#...
if $var == 1
method1(docx)
else
# etc...