Created
August 16, 2017 09:59
-
-
Save defp/50ecc49b64d8372d1a0ba9db4de0e1a7 to your computer and use it in GitHub Desktop.
定义单例方法的方式
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
# 定义单例方法的方式 | |
# 1 | |
class A | |
def self.hi | |
p 'hi' | |
end | |
end | |
# 2 | |
class A | |
class << self | |
def hello | |
p 'hello' | |
end | |
end | |
end | |
# 3 | |
def A.hey | |
p 'hey' | |
end | |
# 4 | |
(class << A; self; end).class_eval do | |
def you | |
p 'you' | |
end | |
end | |
# 5 | |
A.singleton_class.class_eval do | |
def folk | |
p 'folk' | |
end | |
end | |
A.hi | |
A.hello | |
A.hey | |
A.you | |
A.folk | |
p A.singleton_methods |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment