Created
April 15, 2011 16:33
-
-
Save luckydev/921993 to your computer and use it in GitHub Desktop.
for an object -- singleton class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyClass | |
end | |
class << MyClass | |
puts "self is #{self}" | |
end | |
# => self is #<Class:MyClass> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MyModule | |
end | |
class << MyModule | |
puts "self is #{self}" | |
end | |
# => self is #<Class:MyModule> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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