【发布时间】:2012-02-23 05:04:10
【问题描述】:
全部,
升级到 Ruby 1.9.3 后,我正在研究一段代码。它在 Ruby 1.8.7 中运行良好。
代码 greps 一个进程并获取该进程的“rsize”值,将其存储在一个文件中,然后绘制一个图表。但在 ruby 1.9.3 中,我不断收到此错误:
ERROR TypeError: nil can't be coerced into Fixnum
SVG/Graph/Graph.rb:375:in `*': nil 不能被强制转换为 Fixnum (TypeError)
这里是监控Safari进程内存使用的代码
def begin_memprofile
clear_screen
FileUtils.mkdir_p "#{PATH}"
begin
loop do
cmd = "top -l 1 -stats pid,rsize,command |grep Safari | awk '{print $2};'"
process_data = `#{cmd}`.split("\n") # array
arr=process_data[0]
log "Data: #{arr}"
if arr =~ /^[0-9]+M[\+\-]?$/ # accepts rsize values like 80M+, 80M-, 80M
memory= arr.to_s.scan(/\d+/).first.to_i
end
log "Memory: #{memory}"
data = [Time.now.to_i, memory]
write_memory(data) # This function writes data into a csv file
sleep(INTERVAL)
end
end
end
csv 文件将有两列(时间戳、内存)。示例值如下:
1329972936 80
1329972937 50
上面的代码循环运行,直到用户点击 CTRL + C。当用户这样做时,我调用一个函数 从 csv 文件中检索数据并呈现图形
def render_graph
if !File.exist?(CSV_FILENAME)
log "Could not open csv file."
exit_profiler
end
data = []
fields = []
csv_data = {}
# import data
File.open(CSV_FILENAME, "r").each_line do |line|
line = line.strip.split(',')
csv_data[line.first.to_s] = line.last
end
pp "#{csv_data}"
csv_data.each do |row|
content = row.first
log "Creating data point: #{content}:: #{row.last.to_i}"
fields << content
data << row.last.to_i
end
# strip any nil elements
data.compact!
fields.compact!
graph = SVG::Graph::Line.new({
:show_graph_title => true,
:graph_title => 'Memory Footprint (MB)',
:height => 800,
:width => 1024,
:y_title => "RSIZE(MB)",
:x_title => "TIME",
:fields => fields
})
graph.add_data(
:data => data,
:title => "data"
)
graph.show_y_guidelines = true
graph.min_scale_value = 0
graph.show_x_title = true
graph.show_y_title = true
graph.show_data_points = true
graph.show_data_values = true
graph.show_x_labels = true
graph.rotate_x_labels = false
graph.area_fill = true
# config graph
graph.scale_integers = true
graph.key = false
File.open("#{PATH}/memory-#{TIMESTAMP}.svg", 'w') {|f|
f << graph.burn
}
end
我是 ruby 新手,我正在修改别人的代码。我升级到 ruby 1.9.3 因为我想要排序哈希。我不明白为什么会出现此错误。
【问题讨论】:
-
Graph.rb 的第 375 行是哪一行?
-
@fullsailor 我正在使用这个文件 redmine.org/coverage/lib-SVG-Graph-Graph_rb.html 见这个文件的第 75 行
-
我的预感是
y_label_font_size设置为 nil,这会在尝试使用它调用 Fixnum 方法时抛出该异常。