ruby - What is `singleton_class` method in class and object? -
i defined methods specific_data1
, specific_data2
in meta class, , expected these methods belong singleton class:
class user def user.specific_data1 "user specific data defined on user" end class << self def specific_data2 "user specific data defined in meta class" end end end
but neither of methods found in:
user.singleton_class.methods
please me understand singleton_method
on user
class , how useful.
object#methods
returns methods of object. methods defined in class aren't methods of class object, methods of class's instances.
this has nothing singleton classes, it's true classes:
class foo def bar; end end foo.methods.include?(:bar) # => false foo.new.methods.include?(:bar) # => true foo.instance_methods # => [:bar]
here's how works example:
user.methods.grep(/specific/) # => [:specific_data1, :specific_data2] user.singleton_methods # => [:specific_data1, :specific_data2] user.singleton_class.instance_methods.grep(/specific/) # => [:specific_data1, :specific_data2]
Comments
Post a Comment