我一直在玩一些字符串(在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方法列为Class String的一个方法。
当然,在我的irb会话或编辑器中,ruby完全理解执行
"whatdoiknow".upcase
=> "WHATDOIKNOW"
我的问题是:
- String.methods 的输出是什么样的方法?
- 为什么在这个输出中没有列出。upcase方法
- 我怎么能字面上列出字符串的所有方法(例如:当我在搜索某物时)
字符串有一个upcase
方法。但是String
不是字符串,它是一个类,类没有upcase
方法。
如果你想知道一个特定的字符串对象是否有upcase
方法,你应该问这个字符串:
'foo'.methods.include?(:upcase) # => true
或者您应该询问String
类是否为所有字符串定义了实例方法include
:
String.instance_methods.include?(:upcase) # => true
记住:类和其他类一样都是对象。它们有方法,有实例变量,有类
String.methods
是指String
类上的方法;"foo".methods
是指String
类的实例上的方法。
事实上,您链接到的文档确实在"公共实例方法"标题下显示了upcase
。
你应该写:
String.instance_methods.include? :upcase
另一种方式来回顾一下哪个是实例方法,哪个是字符串的方法,在这里作为一个例子:(只注意#
符号和.
符号)
String.new.method(:upcase) #=> #<Method: String#upcase>
String.method(:try_convert) #=> #<Method: String.try_convert>
upcase
方法是一个实例方法,而不是一个类方法。
看String.methods
和"string".methods
的区别
"whatdoiknow".methods.include?(:upcase)
=> true