gpt4 book ai didi

ruby - 为什么方法 to_i 和 to_f 没有出现在 String.methods 中?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:55 24 4
gpt4 key购买 nike

我认为 #methods 方法会列出一个类中的所有方法。为什么当我键入 String.methods.sortto_ito_f 没有出现?

to_i 应该将字符串转换为整数,而 to_f - 将字符串转换为 float 。

String.methods.sort
[:!, :!=, :!~, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__id__,
:__send__, :allocate, :ancestors, :autoload, :autoload?, :class,
:class_eval, :class_exec, :class_variable_defined?,
:class_variable_get, :class_variable_set, :class_variables, :clone,
:const_defined?, :const_get, :const_missing, :const_set, :constants,
:define_singleton_method, :deprecate_constant, :display, :dup,
:enum_for, :eql?, :equal?, :extend, :freeze, :frozen?, :hash,
:include, :include?, :included_modules, :inspect, :instance_eval,
:instance_exec, :instance_method, :instance_methods, :instance_of?,
:instance_variable_defined?, :instance_variable_get,
:instance_variable_set, :instance_variables, :is_a?, :itself,
:kind_of?, :method, :method_defined?, :methods, :module_eval,
:module_exec, :name, :new, :nil?, :object_id, :prepend,
:private_class_method, :private_constant, :private_instance_methods,
:private_method_defined?, :private_methods,
:protected_instance_methods, :protected_method_defined?,
:protected_methods, :public_class_method, :public_constant,
:public_instance_method, :public_instance_methods, :public_method,
:public_method_defined?, :public_methods, :public_send,
:remove_class_variable, :remove_instance_variable, :respond_to?,
:send, :singleton_class, :singleton_class?, :singleton_method,
:singleton_methods, :superclass, :taint, :tainted?, :tap, :to_enum,
:to_s, :trust, :try_convert, :untaint, :untrust, :untrusted?]

最佳答案

因为 Object#methods 列出了给定对象的方法。

要列出给定类的实例方法,请使用 Module#instance_methods:

String.instance_methods.grep /to_i|to_f/ # => [:to_i, :to_f]

或者,如果您有一个实例,您可以搜索它的方法:

'42'.methods.grep /to_i|to_f/ # => [:to_i, :to_f]

关于ruby - 为什么方法 to_i 和 to_f 没有出现在 String.methods 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com