[英]not able to write to file in ruby
class PostCallbacks < XML::SAX::Document
test = "";
out = File.open("output.txt","w");
def start_element(element = "", attributes = [])
@out << element
end
end
gives error: undefined method
<<' for nil:NilClass` 给出错误:nil:NilClass`的undefined method
<<'
why can I not write to file this way? 为什么我不能这样写文件?
Try this: 尝试这个:
class PostCallbacks < XML::SAX::Document
test = "";
def initialize
@out = File.open("output.txt","w");
end
def start_element(element = "", attributes = [])
@out << element
end
end
The error you're getting tells you that @out
isn't initialized properly. 您收到的错误告诉您@out
初始化不正确。 The safest way to do what you're attempting to do is to initialize the instance variable @out
in the constructor, which is to say, the initialize
method. 做您尝试做的最安全的方法是在构造函数中初始化实例变量@out
,也就是说, initialize
方法。
Even better, of course, would be to pass the name of the output file to the constructor, rather than hard-coding it. 当然,更好的办法是将输出文件的名称传递给构造函数,而不是对其进行硬编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.