Question

I have started learning Rails 3.0 and decided to spend sometime learning Pure Ruby 1.9 and wonder if there is a way to View the Object Class since it is always available. Like is there a command that you can type in IRB for example that will display all the methods in Object Class like to_a, to_s, etc.. Thanks for any help

Was it helpful?

Solution

#methods is the method you want. It simply returns an array of symbols, which are all the names of the methods that object responds to.

Object.new.methods

Or more readable in irb:

puts Object.new.methods.sort.to_yaml

Or for the class methods:

Object.methods

One caveat though, some objects allow methods that won't be listed here. Anything implemented with a hook into #method_missing won't show up. This includes a lot of ActiveRecord methods as well as other rails objects.

But so long as nothing tricky is going on, this is the list you seem to want.

OTHER TIPS

To see an object's methods, you can do your_object.methods. For a class, this will be its class methods. To see a class's instance methods, you can do your_class.instance_methods. So to list all the class methods of Object, you'd do Object.methods, and to see all the instance methods of Object, you'd do Object.instance_methods.

Further tip: If you want to see only the methods that a given class implements (not methods inherited from its ancestors), you can pass false as the argument to either of the methods I mentioned earlier. So, for example, String.instance_methods(false) will return a list of instance methods that String implements, but will not return general Object methods like dup and is_a?.

However, if you're trying to learn, looking at the docs for a given class or class extension (such as Rails' additions to String or Date) would probably be better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top