我有以下ruby类:
class Scheme
attr_reader :id, :uri, :labels, :in_schemes, :top_concepts
def initialize(id, uri, labels, in_schemes)
@id = id,
@uri = uri,
@labels = labels
@in_schemes = in_schemes
@top_concepts = Array.new
end
end
我有以下方法遍历给定目录,查找文件(它们的名称如“01”,“01.01.00”等),其中包含一系列特定于语言的类别标签(下面的示例): / p>
def make_schemes(catdir)
concept_schemes = Array.new
Dir.foreach(catdir) do |file|
unless file == "." || file == ".."
id = file.gsub(/\./,"").to_s
uri = "/unbist/scheme/#{id}"
labels = Array.new
in_schemes = Array.new
File.read("#{catdir}/#{file}").split(/\n/).each do |line|
label = JSON.parse(line)
labels << label
end
if id.size > 2
in_schemes = ["/unbist","/unbist/#{id[0..1]}"]
else
in_schemes = ["/unbist"]
end
p "Making new concept scheme with id: #{id}"
concept_scheme = Scheme.new(id, uri, labels, in_schemes)
p concept_scheme
concept_schemes << concept_scheme
end
end
return concept_schemes
end
示例类别文件,名为“#{dir} / 01”。每一行都是正确的JSON,但由于超出此问题范围的原因,整个文件不是。
{ "text": "ﻢﺳﺎﺌﻟ ﻕﺎﻧﻮﻨﻳﺓ ﻮﺴﻳﺎﺴﻳﺓ", "language": "ar" }
{ "text": "政治和法律问题", "language": "zh" }
{ "text": "political and legal questions", "language": "en" }
{ "text": "questions politiques et juridiques", "language": "fr" }
{ "text": "ПОЛИТИЧЕСКИЕ И ЮРИДИЧЕСКИЕ ВОПРОСЫ", "language": "ru" }
{ "text": "cuestiones politicas y juridicas", "language": "es" }
我得到的输出很奇怪。 make_schemes方法中的id变量在构造新Scheme之前已正确设置,但Scheme初始化器似乎在某处混淆并将整个变量集应用于对象的id变量。以下是上述示例的一些输出(为了便于阅读而添加了已清理的换行符:
"Making new concept scheme with id: 01"
#<Scheme:0xa00ffc8
@uri="/scheme/01",
@labels=[{"text"=>"مسائل قانونية وسياسية", "language"=>"ar"}, {"text"=>"政治和法律问题", "language"=>"zh"}, {"text"=>"political and legal questions", "language"=>"en"}, {"text"=>"questions politiques et juridiques", "language"=>"fr"}, {"text"=>"ПОЛИТИЧЕСКИЕ И ЮРИДИЧЕСКИЕ ВОПРОСЫ", "language"=>"ru"}, {"text"=>"cuestiones politicas y juridicas", "language"=>"es"}],
@id=["01", "/scheme/01", [{"text"=>"مسائل قانونية وسياسية", "language"=>"ar"}, {"text"=>"政治和法律问题", "language"=>"zh"}, {"text"=>"political and legal questions", "language"=>"en"}, {"text"=>"questions politiques et juridiques", "language"=>"fr"}, {"text"=>"ПОЛИТИЧЕСКИЕ И ЮРИДИЧЕСКИЕ ВОПРОСЫ", "language"=>"ru"}, {"text"=>"cuestiones politicas y juridicas", "language"=>"es"}]],
@in_schemes=["/"],
@top_concepts=[]>
我在这里缺少什么?是什么造成的?我有一个不同类的构造函数,可以使用类似的逻辑工作。我很困惑。也许有一种方法可以更好地运作?
答案 0 :(得分:3)
尝试修复:
@uri = uri,
为:
@uri = uri
按原样,你告诉Ruby:
@uri = uri, @labels = labels
正如我所读到的那样,这意味着您要将labels
分配给uri, @labels
数组,然后将该数组分配给@uri
。