Discovering Ruby object members?
What is an easy way to find out what methods/properties that a ruby object exposes?
As an example to get member information for a string, in PowerShell, you can do
"" | get-member
In Python,
dir("")
Is there such an easy way to discover开发者_运维百科 member information of a Ruby object?
"foo".methods
See:
http://ruby-doc.org/core/classes/Object.html
http://ruby-doc.org/core/classes/Class.html
http://ruby-doc.org/core/classes/Module.html
Ruby doesn't have properties. Every time you want to access an instance variable within another object, you have to use a method to access it.
Two ways to get an object's methods:
my_object.methods
MyObjectClass.instance_methods
One thing I do to prune the list of inherited methods from the Object base class:
my_object.methods - Object.instance_methods
To list an object's attributes:
object.attributes
There are two ways to accomplish this:
obj.class.instance_methods(false)
, where 'false' means that it won't include methods of the superclass, so for example having:
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
p1 = Person.new 'simon'
p1.class.instance_methods false # => [:name, :name=]
p1.send :name # => "simon"
the other one is with:
p1.instance_variables # => [:@name]
p1.instance_variable_get :@name # => "simon"
Use this:
my_object.instance_variables
object.methods
will return an array of methods in object
精彩评论