irb

March 19th, 2007

irb is a great tool to get more familiar with Ruby and test different snips of code. The more I use Ruby the more time I spend in irb testing out small pieces of code or learning more about what the many methods associated with Ruby objects.

Here are two quick tips when using irb. When you want to see what methods are associated with a specific object you can type this into your irb session:

1
2
>> String.methods
=> ["inspect", "poc", "private_class_method", "const_missing".......]

This will display all the methods associated with the String object. If you’d like to see instance methods, you can type:

1
2
>> String.instance_methods
=> ["%", "select", "[]=", "inspect", "poc", "<<", "each_byte", "method", "clone".....]

This will display all instance methods associated with the String object. If you were to use this on an object you created yourself and you wanted to just see the instance methods you created, you can type:


>> String.instance_methods(false)

also..

1
2
>> String.public_methods
=> ["inspect", "poc", "private_class_method".....]

and..

1
2
>> String.private_methods
=> ["select", "gem_original_require", "global_variables".....]

lastly..

1
2
>> String.protected_methods
=> []

irb is extremely helpful for learning more about Ruby. If you haven’t tried the above, give it a shot and then start playing around with those methods to get a feel for what they do.

What’s your favorite irb trick?

2 Responses to “irb”

  1. Yannick Says:

    Thanks Robert. This was an interesting snip and definitely a good tip for someone learning ruby as well.

  2. Satish Talim Says:

    To all of the above, I like to add the sort method. For example: String.methods.sort

    We get a sorted list of method names – more easier to locate a method.

Sorry, comments are closed for this article.