From: zdennis Date: 2006-04-11T22:56:14+09:00 Subject: Re: Identfying classes in a file dynamically -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Navya Amerineni wrote: > Hi, > > I was trying to identify the classes in a give file at the run time. the following is the code i used. > sc, ec = [], [] > ObjectSpace.each_object(Class) { |c| sc << c } > require 'Roman.rb' > ObjectSpace.each_object(Class) { |c| ec << c } > new_classes = ec - sc > puts new_classes > sc, ec = [], [] > ObjectSpace.each_object(Class) { |c| sc << c } > require 'Roman1.rb' > ObjectSpace.each_object(Class) { |c| ec << c } > new_classes = ec - sc > puts new_classes > > Both roman.rb and roman1.rb has the same class Roman. > the first time i print the new_classes i can see the Roman class in the output but the second one does not print because the class Roman is arleady read previously. > > is there a way i can over come this problem and identify the Roman class twice. > > Way #1, store the new classes in a hash. This way you won't be overriding any classes you've previously loaded. Way #2, use one array to store new classes, and then each time you compute the "new_classes" after you load a file, merge those into your one authoriatize array. This way you won't be overriding any classes you've previously loaded. Way #3, pass a string into a new ruby process which loads the files and outputs the new classes. Read these in and then use Way #1 or Way #2 to store the classes. This is a bit hackish, but it works and it leaves your toplevel ruby process namespace alone. Here is the idea of Way #3 str =<<-'EOT' def count_classes( arg ) arr = [] ObjectSpace.each_object( arg ){ |c| arr << c } arr end orig_classes = count_classes( Class ) require "load" new_classes = count_classes( Class ) - orig_classes puts new_classes.join( "\n" ) EOT child = IO.popen( "ruby -e '#{str}'", "r" ) new_classes = child.readlines.map!{ |s| s.chomp! } puts new_classes Zach -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEO7aRMyx0fW1d8G0RAjPQAJ0YvkXA1bRmS7VCWlxw/n5CeFUD9ACcD100 MN9Ii+gFYzpg56Veh4YFd2g= =vGHj -----END PGP SIGNATURE-----