2007/11/16 said:
There's a bit of a Heisenberg problem here, in that the act of
measuring alters the result.
Singleton instance classes aren't created until they are needed, but
one of the things which creates them is class <<x;end so you're really
not checking whether or not the singleton class already exists this
way.
Another way would be
!var.singleton_methods.empty?
BTW, your 8.singleton_class will fail, Fixnums can't have singleton classes.
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/
Thanks!
I see.
In fact I want to create singleton class if it is possible.
I guess checking if singleton class already exists should be tricky
coding or impossible.
Let's look at the code:
class Object
def singleton_class
class <<self; self; end rescue nil
end
end
["abc", 8].each do |a|
puts "\nObject: #{a}"
puts !a.singleton_methods.empty?
puts a.singleton_class
puts !a.singleton_methods.empty?
end
Output is
Object: abc
false
#<Class:#<String:0x2b28c50>>
false
Object: 8
false
nil
false
So it looks like expression
!a.singleton_methods.empty?
can miss existence of singleton class.
But in fact these two problems have pragmatic sense:
1) Get singleton class if it is possible
2) Check if objects has singleton methods
While this one -- not :
3) Check if singleton class exists
(now I understand that there is no use case for it)
Artem