Thursday, September 27, 2007

Ruby has a "methods" method to see all available methods

So it turns out that Ruby has a few methods that can really help you figure out what you're doing when you're working with sparsely documented APIs or you just want a quick reference.

I've used the "inspect" method for a long time. You can basically see all of the class members and sometimes other useful information. For example:

irb(main):001:0> s = "My String"
=> "My String"
irb(main):002:0> s.inspect
=> "\"My String\""

irb(main):003:0> a = [1, 2, 3]
=> [1, 2, 3]
irb(main):004:0> a.inspect
=> "[1, 2, 3]"

The inspect method can give you a good idea of what data is in a particular object. But what if you want to see all methods an object holds? Well duh.... use #methods.

irb(main):001:0> require 'pp'
=> true
irb(main):002:0> s = "My String"
=> "My String"
irb(main):003:0> pp s.methods.sort
=> nil

Useful, huh?

No comments:

Post a Comment