Ruby NoMethodError-template.rb:38:in`<;main>';:未定义的方法`模板';对于主:对象(NoMethodError)
这是我的代码,我正在尝试运行该方法,但它一直在为main:Object踢出一个Ruby NoMethodError-template.rb:38:in`<;main>';:未定义的方法`模板';对于主:对象(NoMethodError),ruby,Ruby,这是我的代码,我正在尝试运行该方法,但它一直在为main:Object踢出一个NoMethodError:undefined方法“template” 有人能帮忙吗 module Template attr_accessor :source_template, :req_id def initialize (source_template, req_id) @source_template = source_template @req_id = req_id end
NoMethodError:undefined方法“template”
有人能帮忙吗
module Template
attr_accessor :source_template, :req_id
def initialize (source_template, req_id)
@source_template = source_template
@req_id = req_id
end
def self.template(source_template, req_id)
template = String.new(@source_template)
template_split_begin = template.index("e")
template_split_end = template_split_begin + 6
template_part_one =
String.new(self.template[0..(template_split_begin-1)])
template_part_two =
String.new(self.template[template.length..template_split_end])
code = String.new(@req_id)
final_template =
String.new(template_part_one + code + template_part_two)
template_split_begin_alt = template.index("a")
template_split_end_alt = template_split_begin_alt + 9
template_alt =
String.new(self.template[0..(template_split_begin_alt-1)])
template_part_two =
String.new(self.template[template.length..template_split_begin_alt])
altcode = code[5..7] - code[0..4]
final_alt_template =
String.new(template_part_one_alt + altcode + template_part_two_alt)
end
end
sample = "Green", 8
template("Blue", 6)
好的,我想我需要更深入的解释
initialize
方法毫无意义。您应该只在类中使用它attr\u访问器:source\u模板,:req\u id
在代码中没有意义sample=“Green”,8
是未使用的变量模板(“蓝色”,6)
,而不是在定义它的模块上调用模板(“蓝色”,6)
,这就是为什么我说您应该使用模板
如果你改变了它,你就不会再有这个错误了。但是,从您的代码来看,您似乎缺少该语言的基本知识,因此我建议您在开始编写代码之前先阅读一些关于Ruby的书籍。它仍然为模板方法提供了相同的名称。我认为我的模板方法中的代码是不相关的,因为我不能在定义方法的同时调用方法本身。对吗?@user1203225我更新了答案。对不起,我不明白你的问题。在Ruby中没有“自己调用方法”之类的东西,不用担心。谢谢你的帮助,我将努力学习Ruby。