Skip to content

Instantly share code, notes, and snippets.

@defp
Created August 16, 2017 09:59
Show Gist options
  • Save defp/50ecc49b64d8372d1a0ba9db4de0e1a7 to your computer and use it in GitHub Desktop.
Save defp/50ecc49b64d8372d1a0ba9db4de0e1a7 to your computer and use it in GitHub Desktop.
定义单例方法的方式
# 定义单例方法的方式
# 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