概述
我正在通过生成XML文件的数据库查询在我的ruby脚本中创建对象。因此,每次只处理一个XML文件,所有标记都是通用的,因此可以轻松地添加其他查询。
问题
我一次创建一个对象,然后将它添加到列表中,如下所示:
#create a new BarChart
bar_chart = BarChart.new(title, data, labels, x_axis, y_axis);
#add the chart to the chart list
charts.push(bar_chart)但是每次我处理一个XML文件时,如果我想要创建一个BarChart,我就会重用变量bar_chart,这会导致我的对象的数据被覆盖。我在找一条绕过这条路的路。
我试过什么
我试图将对象的副本传递到列表中,但这仍在覆盖数据。
#create a new BarChart
bar_chart = BarChart.new(title, data, labels, x_axis, y_axis);
#add the chart to the chart list
charts.push(bar_chart.clone)和
#create a new BarChart
bar_chart = BarChart.new(title, data, labels, x_axis, y_axis);
#add the chart to the chart list
charts.push(bar_chart.dup)任何帮助/想法都会很好。谢谢。
编辑,这里有更多的信息,是我处理的方法。
def self.process_xml_files2(filenames)
labels = []
data = []
charts = []
title = nil
type = nil
x_axis = nil
y_axis = nil
#retrieve needed data from the XML file
filenames.each do |filename|
f = File.new(filename)
#create a document
doc = Document.new(f)
doc.elements.each("//row/field") do |e|
tag = e.attributes['name']
text = e.text
#search for tags and append correct data to lists
if tag.casecmp('Type') == 0
type = text
elsif tag.casecmp('Title') == 0
title = text
elsif tag.casecmp('Labels') == 0
labels.push(text)
elsif tag.casecmp('Data') == 0
data.push(text)
elsif tag.casecmp('X-Axis') == 0
x_axis = text
elsif tag.casecmp('Y-Axis') == 0
y_axis = text
end
end
f.close()
#test for correct chart parameters
raise "Not Enough Arguments"
if title == nil or type == nil or data.empty? or labels.empty?
#process the raw chart data
if type.casecmp('Bar') == 0
#test for labels
raise "Bar Charts require X and Y axis labels"
if x_axis == nil or y_axis == nil
#format the data for the bar chart
data = BarChart.barify_data(data)
#create a new BarChart
bar_chart = BarChart.new(title, data, labels, x_axis, y_axis);
#add the chart to the chart list
charts.push(bar_chart)
elsif type.casecmp('Pie') == 0
#format data and labels for the pie chart
data = PieChart.pieify_data(data)
#create a new Pie Chart
pie_chart = PieChart.new(title, data, labels)
#add the pie chart to the chart list
charts.push(pie_chart.clone)
else
raise "Invalid Chart Type: Not Pie or Bar"
end
end
#write all the charts to the images directory
charts.each do |ch|
puts ch.url + "\n\n"
ch.download_image(ch.url, ch.title)
end
end发布于 2011-08-01 18:17:30
从代码中可以看到,您正在重用labels和data对象(注意:对象,而不是变量!)对于您添加到列表中的每一张图表。看来你该搬家了
labels = []
data = []filenames.each循环中的初始化。
https://stackoverflow.com/questions/6902058
复制相似问题