57

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?

dance2die
  • 35,807
  • 39
  • 131
  • 194

6 Answers6

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

noodl
  • 17,143
  • 3
  • 57
  • 55
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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
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
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
  • 17
    #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 Jan 20 '11 at 13:07
  • @noodl, thanks. I meant instance_variables, but have too much Rails in my head :) – Mark Thomas Jan 20 '11 at 17:06
  • 2
    Kind of old, but `instance_variables` doesnt seem to show uninitialized variables, was hoping it showed attributes set with `attr_accessor` or its cousins – Karthik T Oct 17 '13 at 05:11
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"
Flip
  • 6,233
  • 7
  • 46
  • 75
sescob27
  • 647
  • 1
  • 8
  • 17
7

Use this:

my_object.instance_variables
Nimo
  • 7,984
  • 5
  • 39
  • 41
2
object.methods

will return an array of methods in object

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194