X.methods命令可以列出该对像的所有方法
前段时间有人问,Ruby下面有没有类似Python中的"dir(X)"这样的列出该对像所有方法/属性的命令,这样就不用去翻文档了。当时我说要找找看。
今天就想起来了,Ruby中有个methods命令可以达到这样的目的。不过只能列出方法,属性怎么列出来,从methods的返回中,应该可以看出端倪。
1、在命令行下,输入irb,进入ruby的交互式环境;
2、对任何一个对像、类,都调用它的method方法试试,会有惊喜
代码:
irb(main):002:0> a = ""
=> ""
irb(main):003:0> a.methods
=> ["respond_to?", "display", "%", "index", "select", "<<", "to_a", "oct", "slic
e", "type", "chomp", "length", "protected_methods", "upcase", "partition", "sub!
", "squeeze", "upcase!", "crypt", "delete!", "eql?", "to_sym", "*", "grep", "ins
tance_variable_set", "lstrip!", "+", "is_a?", "center", "hash", "send", "to_s",
"rindex", "between?", "reject", "split", "class", "size", "strip", "tainted?", "
private_methods", "count", "succ!", "downcase", "gsub!", "__send__", "squeeze!",
"downcase!", "intern", "member?", "untaint", "next", "find", "each_with_index",
"rstrip!", "each_line", "id", "sub", "to_i", "slice!", "instance_eval", "replac
e", "collect", "inspect", "tr", "reverse", "all?", "clone", "entries", "lstrip",
"public_methods", "capitalize", "chop!", "extend", "capitalize!", "scan", "free
ze", "detect", "zip", "each_byte", "__id__", "gsub", "<=>", "to_f", "casecmp", "
<", "methods", "map", "==", "tr_s", "empty?", "to_str", "===", "any?", "tr!", ">
", "nil?", "rstrip", "match", "sort", "dup", "instance_variables", "chomp!", "in
clude?", "next!", "swapcase", "min", ">=", "instance_of?", "method", "swapcase!"
, "ljust", "<=", "upto", "find_all", "sum", "hex", "each", "object_id", "insert"
, "reverse!", "chop", "=~", "singleton_methods", "dump", "inject", "delete", "co
ncat", "tr_s!", "unpack", "equal?", "taint", "succ", "sort_by", "frozen?", "inst
ance_variable_get", "max", "[]", "strip!", "kind_of?", "rjust", "[]="]
irb(main):004:0> String.methods
=> ["to_a", "respond_to?", "ancestors", "display", "module_eval", "const_missing
", "type", "protected_methods", "instance_methods", "public_method_defined?", "s
uperclass", "eql?", "instance_variable_set", "const_get", "is_a?", "hash", "send
", "to_s", "class_eval", "class_variables", "class", "public_instance_methods",
"autoload", "tainted?", "private_methods", "private_method_defined?", "__send__"
, "included_modules", "untaint", "const_set", "id", "instance_method", "inspect"
, "instance_eval", "clone", "public_methods", "protected_instance_methods", "pro
tected_method_defined?", "extend", "freeze", "public_class_method", "allocate",
"__id__", "<=>", "<", "methods", "==", "===", "autoload?", ">", "nil?", "dup", "
instance_variables", "include?", "private_instance_methods", ">=", "instance_of?
", "const_defined?", "method", "<=", "name", "private_class_method", "new", "obj
ect_id", "=~", "singleton_methods", "method_defined?", "equal?", "taint", "froze
n?", "constants", "instance_variable_get", "kind_of?"]
从中可以看到,这个对像本身是有methods这个方法的,类似的还有public_class_method,instance_variable等等有用的东东,自己发掘吧。
学Ruby的时候,可以在命令行下,亲自敲打一下这些对像\类的方法,熟悉一下它们的用法,非常有意思的。
|