58

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?

6 Answers 6

76
"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

Sign up to request clarification or add additional context in comments.

1 Comment

"foo".methods - Object.methods to be more specific
26

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.

1 Comment

It's great to know that everything is a method. Thanks Andrew
17

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

3 Comments

#attributes is AR specific; for a plain ruby object there's #instance_variables. Also, you can pass false as an argument to #methods to skip inherited ones.
@noodl, thanks. I meant instance_variables, but have too much Rails in my head :)
Kind of old, but instance_variables doesnt seem to show uninitialized variables, was hoping it showed attributes set with attr_accessor or its cousins
9

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"

Comments

8

Use this:

my_object.instance_variables

Comments

2
object.methods

will return an array of methods in object

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.