我想查找在運行時在ruby腳本中創建的類的列表/總和。如何獲得在ruby腳本中創建的所有對象類型的列表
我這樣做
# rewrite class in order to display ClassName when GCed"
#
$objs = []
class Class
alias oldNew new
def new(*args)
inst = oldNew(*args)
$objs << inst.class.name unless $objs.include?(inst.class.name)
inst
end
end
# some code
puts $bjs
有沒有更好的方式來做到這一點?
我曾嘗試使用:
$objs = []
class Class
alias oldNew new
def new(*args)
inst = oldNew(*args)
ObjectSpace.define_finalizer(inst, proc {|id| puts "Finalizer one on #{id.name}" })
inst
end
end
但我沒有輸出。
僅供參考我測試的一些代碼使用C擴展名。
編輯 更具體的代碼:
require "gtk3"
require "objspace"
$objs = []
class Class
alias oldNew new
def new(*args)
inst = oldNew(*args)
# This doesn't work
# ObjectSpace.define_finalizer(inst, proc {|id| puts "Finalizer one on #{id.name}" })
$objs << inst.class.name unless $objs.include?(inst.class.name)
inst
end
end
TITLE_COLUMN = 0
AUTHOR_COLUMN = 1
CHECKED_COLUMN = 2
model = Gtk::TreeStore.new(String, String, TrueClass)
iter = model.append(nil)
iter[TITLE_COLUMN] = "The Principle of Reason"
iter[AUTHOR_COLUMN] = "Martin Heidegger"
iter[CHECKED_COLUMN] = false
iter = model.append(nil)
iter.set_values(["The Art of Computer Programming", "Donald E. Knuth", true])
# append child
child_iter = model.append(iter)
child_iter[TITLE_COLUMN] = "Volume 1: Fundamental Algorithms"
# append another child
child_iter = model.append(iter)
child_iter.set_value(TITLE_COLUMN, "Volume 2: Seminumerical Algorithms")
child_iter.set_value(CHECKED_COLUMN, true)
# append another child
child_iter = model.append(iter)
child_iter.set_values(["Volume 3: Sorting and Searching", "Donald E. Knuth", true])
def treeview_widget_of(model)
treeview = Gtk::TreeView.new(model)
treeview.append_column(Gtk::TreeViewColumn.new("Title", Gtk::CellRendererText.new, { :text => TITLE_COLUMN }))
treeview.append_column(Gtk::TreeViewColumn.new("Author", Gtk::CellRendererText.new, { :text => AUTHOR_COLUMN }))
treeview.append_column(Gtk::TreeViewColumn.new("Author", Gtk::CellRendererToggle.new, { :active => CHECKED_COLUMN }))
treeview
end
def display_model(model)
win = Gtk::Window.new(:toplevel)
win.title = "Simple Gtk::TreeStore"
win.add(treeview_widget_of(model))
win.show_all
win.signal_connect("destroy") { Gtk.main_quit }
Gtk.main
end
display_model(model)
puts $objs.inspect
編輯2
["Gio::Loader", "Class", "Module", "GObjectIntrospection::TypeTag", "GObjectIntrospection::Direction", "GObjectIntrospection::FieldInfoFlags", "GObjectIntrospection::ScopeType", nil, "LoadError", "Gdk::Loader", "Gtk::Loader", "Gtk::TreeStore", "GLib::Value", "Gtk::Window", "Gtk::TreeView", "Gtk::CellRendererText", "Gtk::TreeViewColumn", "Gtk::CellRendererToggle"]
你能舉幾個例子,即填寫'一些代碼#some code'? – Stefan
當然。查看編輯部分 – cedlemo
你的問題是什麼?你共享的代碼有一些輸出 - 那個輸出有什麼錯誤,你的期望輸出是什麼。 –