Get list of a class' instance methods
You actually want TestClass.instance_methods
, unless you're interested in what TestClass
itself can do.
class TestClass
def method1
end
def method2
end
def method3
end
end
TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]
Or you can call methods
(not instance_methods
) on the object:
test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]
How do I get list of methods in a Python class?
An example (listing the methods of the optparse.OptionParser
class):
>>> from optparse import OptionParser
>>> import inspect
#python2
>>> inspect.getmembers(OptionParser, predicate=inspect.ismethod)
[([('__init__', <unbound method OptionParser.__init__>),
...
('add_option', <unbound method OptionParser.add_option>),
('add_option_group', <unbound method OptionParser.add_option_group>),
('add_options', <unbound method OptionParser.add_options>),
('check_values', <unbound method OptionParser.check_values>),
('destroy', <unbound method OptionParser.destroy>),
('disable_interspersed_args',
<unbound method OptionParser.disable_interspersed_args>),
('enable_interspersed_args',
<unbound method OptionParser.enable_interspersed_args>),
('error', <unbound method OptionParser.error>),
('exit', <unbound method OptionParser.exit>),
('expand_prog_name', <unbound method OptionParser.expand_prog_name>),
...
]
# python3
>>> inspect.getmembers(OptionParser, predicate=inspect.isfunction)
...
Notice that getmembers
returns a list of 2-tuples. The first item is the name of the member, the second item is the value.
You can also pass an instance to getmembers
:
>>> parser = OptionParser()
>>> inspect.getmembers(parser, predicate=inspect.ismethod)
...
At runtime, how do I list all Objective-C class methods for a given class?
Each Objective-C @implementation
is represented at run time by an object, the “class object”. The class object manages the method dictionary for instance methods.
For example, for UIView
, there is an UIView
class object. When you call NSClassFromString(@"UIView")
(or [UIView class]
or [UIView self]
), it returns the UIView
class object. The UIView
class object manages the method dictionary for UIView
instance methods.
The UIView
class object is itself an instance of another class, called the UIView
metaclass. The UIView
metaclass is represented by another class object, the UIView
metaclass object. The UIView
metaclass object manages the method dictionary for UIView
class methods.
So, to get the class method list for UIView
, you need to pass the UIView
metaclass object to class_copyMethodList
.
Class UIView_class = NSClassFromString(@"UIView");
Class UIView_metaclass = object_getClass(UIView_class);
unsigned int count;
Method *classMethods = class_copyMethodList(UIView_metaclass, &count);
Retrieve list of instance methods that are defined in rails class excluding inherited and included methods
Many (most? all?) of those extra methods you are seeing are being created using Module#define_method
. If you dig deep in the source for active_support
, you'll see that. (You aren't directly including active_support
, but it's being pulled in by one or more of the Mongoid
modules.)
So these are in fact valid instance methods of your model class, which is why they are included in instance_methods(false)
. Other methods that are defined "conventionally" in the mixins, such as #freeze
, are reported by instance_methods(true)
, but not by instance_methods(false)
.
I think you may have to do something to filter the list based on the source location. Something along these lines:
my_methods = Product.instance_methods(false).select do |m|
Product.instance_method(m).source_location.first.ends_with? '/product.rb'
end
How to get instance variable of a class list by using a class method?
You can do :
class Dog:
dogs = []
def __init__(self, name):
self.name = name
self.dogs.append(self)
@classmethod
def num_dogs(cls):
return len(cls.dogs)
@classmethod
def dogs_names(cls):
names = [] # create a new list
for i in range(len(cls.dogs)):
names.append(cls.dogs[i].name) # append each name one by one to the list
return names # return the full list at the end
@staticmethod
def bark(n):
"""barks n times"""
for _ in range(n):
print("Bark! ")
tim = Dog("Tim")
jim = Dog("Jim")
print(Dog.num_dogs())
print(Dog.dogs_names())
you can also use list conprehension :
@classmethod
def dogs_names(cls):
return [dog.name for dog in cls.dogs]
Method, which return list of instance methods
I would like to create method, where as argument i can put some object
and it will detect, what class is it and return me list of all
instance methods
class Person
def self.instance_methods(object)
object.class.instance_methods(false)
end
end
Usage:
c = Client.new("1", "2", "3", "4")
Person.instance_methods(c)
#=> returns an array of all instance methods defined in Client class
Also is there some option to choose only methods, which don't require
any argument?
Yes, you have to check method
's arity
and select those, which has zero:
class Person
def self.instance_methods_with_arity_zero(object)
object.class.instance_methods(false).map do |method|
object.method(method).arity.zero?
end
end
end
Usage:
c = Client.new("1", "2", "3", "4")
Person.instance_methods_with_arity_zero(c)
#=> returns an array of instance methods which take no arguments defined in Client class
The latter method can be shortened to use the first defined method:
def self.instance_methods_with_arity_zero(object)
# we are using the previously defined instance_methods method
instance_methods(object).map { |method| object.method(method).arity.zero? }
end
Related Topics
Best Way to Convert Strings to Symbols in Hash
Rails 4: Before_Filter Vs. Before_Action
Is There a Performance Gain in Using Single Quotes VS Double Quotes in Ruby
Is It Good Style to Explicitly Return in Ruby
What's Different Between Each and Collect Method in Ruby
What Are the Restrictions For Method Names in Ruby
How to Configure Webrick to Use Ssl in Rails
Custom Authentication Strategy For Devise
Difference Between Various Variables Scopes in Ruby
When Should I Use Struct Vs. Openstruct
Ruby/Ruby on Rails Memory Leak Detection
How to Download a Binary File Over Http