Discovering Ruby object members?

RubyDiscoverability

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

Solution 2 - Ruby

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.

Solution 3 - Ruby

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

Solution 4 - Ruby

Use this:

my_object.instance_variables

Solution 5 - Ruby

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"

Solution 6 - Ruby

object.methods

will return an array of methods in object

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondance2dieView Question on Stackoverflow
Solution 1 - RubynoodlView Answer on Stackoverflow
Solution 2 - RubyAndrew GrimmView Answer on Stackoverflow
Solution 3 - RubyMark ThomasView Answer on Stackoverflow
Solution 4 - RubyNimoView Answer on Stackoverflow
Solution 5 - Rubysescob27View Answer on Stackoverflow
Solution 6 - RubyArnaud Le BlancView Answer on Stackoverflow