Skip to content

Instantly share code, notes, and snippets.

@luckydev
Created April 15, 2011 16:33
Show Gist options
  • Save luckydev/921993 to your computer and use it in GitHub Desktop.
Save luckydev/921993 to your computer and use it in GitHub Desktop.
for an object -- singleton class
class MyClass
end
class << MyClass
puts "self is #{self}"
end
# => self is #<Class:MyClass>
module MyModule
end
class << MyModule
puts "self is #{self}"
end
# => self is #<Class:MyModule>
class MyClass
def my_instance_method
puts "this is an instance method"
end
#self here is MyClass
class << self
def count_objects
"counting objects..DONE"
end
end
end
#assigning self explicitly
class << MyClass
def find_average
"finding average..DONE"
end
end
p MyClass.count_objects # => "counting objects..DONE"
p MyClass.find_average # => "finding average..DONE"
class MyClass
end
my_object = MyClass.new
class << my_object
puts "self is #{self}"
end
# => self is #<Class:#<MyClass:0x0000010086cf58>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment