gpt4 book ai didi

ruby - 为什么当我调用类的实例方法时,初始化不显示为方法?

转载 作者:数据小太阳 更新时间:2023-10-29 07:12:41 25 4
gpt4 key购买 nike

我正在写一篇关于在 Ruby 中几乎一切都是对象的博客文章,我试图通过以下示例来展示这一点:

class CoolBeans
attr_accessor :beans

def initialize
@bean = []
end

def count_beans
@beans.count
end

end

所以从类中我们可以看出它有 4 个方法(当然,除非我错了):

  1. 它可以在创建新实例时初始化一个默认的空bean数组
  2. 它可以计算它有多少个 bean
  3. 它可以读取它有多少个 bean(通过 attr_accessor)
  4. 它可以向空数组写入(或添加)更多 bean(也通过 attr_accessor)

但是,当我询问类本身它有哪些实例方法时,我没有看到默认的 initialize 方法:

CoolBeans.new.class.instance_methods
# => [:beans, :beans=, :count_beans, :lm, :lim, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :itself, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :extend, :display, :method, :public_method, :singleton_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]

这是否意味着初始化方法不是实例方法?如果不是,为什么它不显示为类 CoolBeans 可用的方法?

最佳答案

instance_methods返回一组 publicprotected 方法。但是,initialize 自动private ref .

CoolBeans.private_instance_methods
# => [:initialize, :default_src_encoding, :irb_binding, :initialize_copy, :initialize_dup, :initialize_clone, :sprintf, :format, :Integer, :Float, :String, :Array, :Hash, :warn, :raise, :fail, :global_variables, :__method__, :__callee__, :__dir__, :eval, :local_variables, :iterator?, :block_given?, :catch, :throw, :loop, :respond_to_missing?, :trace_var, :untrace_var, :at_exit, :syscall, :open, :printf, :print, :putc, :puts, :gets, :readline, :select, :readlines, :`, :p, :test, :srand, :rand, :trap, :load, :require, :require_relative, :autoload, :autoload?, :proc, :lambda, :binding, :caller, :caller_locations, :exec, :fork, :exit!, :system, :spawn, :sleep, :exit, :abort, :Rational, :Complex, :set_trace_func, :gem, :gem_original_require, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined, :method_missing]
# ^^^^^^^^^^^

关于ruby - 为什么当我调用类的实例方法时,初始化不显示为方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32505558/

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