Get all local variables or available methods from irb?
Asked Answered
R

3

25

When I go into irb and type in a command that does not exist I get an error stating

"undefined local variable or method 'my_method' for main:Object (NameError)"

Is there a way to just get a list of what local variables or methods ARE available? This would be really useful for exploring ruby.

Rhiana answered 25/4, 2011 at 3:40 Comment(0)
O
30

Look for methods in the Kernel, Object and Module : e.g. local_variables, instance_methods, instance_variables.

Other great methods in there. inspect is another one.

Overglaze answered 25/4, 2011 at 3:48 Comment(3)
@sawa, inspect will show instance_variables too (i.e. unless it has been overridden for a class to show something else instead)Overglaze
can someone explain how this guy gets the prompt: "show all available 152) methods?" youtube.com/watch?v=J_9H1WPV2Ws#t=0m15sGracia
@lukemh, type [1,2]. into irb and press TAB twice. The feature in general is called completion / auto-completion.Overglaze
R
16

Great answers.
As you explore, you have these at your disposal:

obj.private_methods 
obj.public_methods 
obj.protected_methods 
obj.singleton_methods

and

MyClass.private_instance_methods 
MyClass.protected_instance_methods 
MyClass.public_instance_methods

Usage like :

obj.public_methods.sort

Can make review easier too.

Some special cases exist like

String.instance_methods(false).sort

... will give you only the instance methods defined in the String class, omitting the classes it inherited from any ancestors. As I expect you know, you can see more here: http://www.ruby-doc.org/docs/ProgrammingRuby/ but it's not as fun as inspecting and reflecting in irb.

Happy exploring -

Perry

Roll answered 25/4, 2011 at 11:44 Comment(0)
Y
6

To find out instance variables, you can use Kernel#instance_variables as Zabba pointed out.

For methods available on an object, I use my_object.methods - Object.methods to find out what non-obvious methods are available to my object. This narrows down the list and is considerably easy to read.

Yuille answered 25/4, 2011 at 5:42 Comment(2)
You should probably change that to my_object.methods.sort - Object.new.methods -- as it stands, you're subtracting Object's class methods from the list of my_object's instance methods.Odd
True. However in Ruby, Object.class is Class which is an instance of the class Class, so it still has the methods from Object.methods.Yuille

© 2022 - 2024 — McMap. All rights reserved.