Why doesn't initialization appear as a method when I call the methods of the class instance?

I am writing a blog post about how almost everything is an object in Ruby, and I am trying to show this in the following example:

class CoolBeans attr_accessor :beans def initialize @bean = [] end def count_beans @beans.count end end 

So, looking at the class, we can say that it has 4 methods (unless, of course, I'm wrong):

  • It can initialize the default beans array when creating a new instance.
  • It can count how many beans has
  • He can read how many beans he has (via attr_accessor )
  • It can write (or add) more beans to an empty array (also via attr_accessor )

However, when I ask the class itself which instance methods it has, I don’t see the initialize method by default:

 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__] 

Does this mean that the initialize method is not an instance method? If not, why doesn't it appear as a method available to the CoolBeans class?

+5
source share
1 answer

instance_methods returns an array of public and protected methods. However, initialize automatically a 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] # ^^^^^^^^^^^ 
+9
source

All Articles