概述
我在我的 ruby 脚本中从生成 XML 文件的数据库查询中创建对象。我已经做到了,因此一次只处理一个 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)
任何帮助/想法都会很棒。谢谢。
编辑,更多信息 这是我进行 XML 处理的方法。
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