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
["%",
"*",
"+",
"<",
"<<",
"<=",
"<=>",
"==",
"===",
"=~",
">",
">=",
"[]",
"[]=",
"__id__",
"__send__",
"all?",
"any?",
"between?",
"capitalize",
"capitalize!",
"casecmp",
"center",
"chomp",
"chomp!",
"chop",
"chop!",
"class",
"clone",
"collect",
"concat",
"count",
"crypt",
"delete",
"delete!",
"detect",
"display",
"downcase",
"downcase!",
"dump",
"dup",
"each",
"each_byte",
"each_line",
"each_with_index",
"empty?",
"entries",
"eql?",
"equal?",
"extend",
"find",
"find_all",
"freeze",
"frozen?",
"grep",
"gsub",
"gsub!",
"hash",
"hex",
"id",
"include?",
"index",
"inject",
"insert",
"inspect",
"instance_eval",
"instance_of?",
"instance_variable_get",
"instance_variable_set",
"instance_variables",
"intern",
"is_a?",
"kind_of?",
"length",
"ljust",
"lstrip",
"lstrip!",
"map",
"match",
"max",
"member?",
"method",
"methods",
"min",
"next",
"next!",
"nil?",
"object_id",
"oct",
"partition",
"pretty_inspect",
"pretty_print",
"pretty_print_cycle",
"pretty_print_inspect",
"pretty_print_instance_variables",
"private_methods",
"protected_methods",
"public_methods",
"reject",
"replace",
"respond_to?",
"reverse",
"reverse!",
"rindex",
"rjust",
"rstrip",
"rstrip!",
"scan",
"select",
"send",
"singleton_methods",
"size",
"slice",
"slice!",
"sort",
"sort_by",
"split",
"squeeze",
"squeeze!",
"strip",
"strip!",
"sub",
"sub!",
"succ",
"succ!",
"sum",
"swapcase",
"swapcase!",
"taint",
"tainted?",
"to_a",
"to_f",
"to_i",
"to_s",
"to_str",
"to_sym",
"tr",
"tr!",
"tr_s",
"tr_s!",
"type",
"unpack",
"untaint",
"upcase",
"upcase!",
"upto",
"zip"]
=> nil


Useful, huh?

No comments:

Post a Comment