我一直在玩字符串(在 irb 中),发现自己无法理解以下代码的含义:
String.methods
=> [:try_convert, :allocate, :new, :superclass, :freeze, :===, :==, :<=>, :<, :<=, :>,
:>=, :to_s, :included_modules, :include?, :name, :ancestors, :instance_methods,
:public_instance_methods, :protected_instance_methods, :private_instance_methods,
:constants, :const_get, :const_set, :const_defined?, :const_missing, :class_variables,
:remove_class_variable, :class_variable_get, :class_variable_set,
:class_variable_defined?, :public_constant, :private_constant, :module_exec, :class_exec,
:module_eval, :class_eval, :method_defined?, :public_method_defined?,
:private_method_defined?, :protected_method_defined?, :public_class_method,
:private_class_method, :autoload, :autoload?, :instance_method, :public_instance_method,
:nil?, :=~, :!~, :eql?, :hash, :class, :singleton_class, :clone, :dup, :initialize_dup,
:initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?,
:inspect, :methods, :singleton_methods, :protected_methods, :private_methods,
:public_methods, :instance_variables, :instance_variable_get, :instance_variable_set,
:instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send,
:respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method,
:define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=,
:instance_eval, :instance_exec, :__send__, :__id__]
因此输出中不包含众所周知的方法“upcase”,我尝试以这种方式接收它:
String.methods.include?(:upcase)
=> false # mother of god, I am shocked!
但是http://ruby-doc.org/core-2.0/String.html#method-i-upcase将 .upcase 方法列为类字符串的方法。
当然,在我的 irb-sessions 或编辑器中,ruby 完全理解执行
"whatdoiknow".upcase
=> "WHATDOIKNOW"
我的问题是:
- String.methods 的输出是什么类型的方法
- 为什么此输出中未列出 .upcase 方法
- 我如何从字面上列出 String 的所有方法(例如,当我搜索某些东西时)