Skip to content

Instantly share code, notes, and snippets.

@duairc
Created September 4, 2009 17:09
Show Gist options
  • Save duairc/180993 to your computer and use it in GitHub Desktop.
Save duairc/180993 to your computer and use it in GitHub Desktop.
Given an arbitary metaclass, return the object of which the given metaclass is a metaclass
class Fixnum
def to_fixnum
self
end
end
class Bignum
def to_fixnum
self[Fixnum::BITS] == 1 ? ~(~(self) & Fixnum::MAX) : self & Fixnum::MAX
end
end
class Object
def metaclass
class << self; self; end
end
end
class Module
def const_get_full(name)
first, rest = name.to_s.split(/::/, 2)
rest ? const_get(first).const_get_full(rest) : const_get(first)
end
end
class Class
def unmetaclass(string = inspect.gsub(/^<\#Class:(.*)>$/, '\1'), recur = 0)
begin
Object.const_get_full(string)
rescue NameError
string.gsub!(/^\#<(?:[A-Z](?:[A-Za-z_]*)(?:::)?)+:(.*)>$/, '\1')
if string =~ /^0x[a-f0-9]+$/
ObjectSpace._id2ref((string.to_i(16) / 2).to_fixnum)
else
object = unmetaclass(string, recur + 1)
recur > 0 ? object.metaclass : object
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment