如何在课程中获得所有自定义方法?

时间:2013-05-23 17:58:05

标签: ruby methods

module Test
  class A
    def hi
      p 'hi'
    end

    def bye
      p 'bye'
    end

    puts methods.sort
    p '---------'
    puts methods.sort - Object.methods
  end
end

第二个puts不打印任何内容,第一个不打印'hi'和'bye'。为什么呢?

2 个答案:

答案 0 :(得分:5)

因为这两行都是在A类本身的范围内执行的,而hibye是该类的实例方法。试试这个:

module Test
  class A
    def hi
      p 'hi'
    end

    def bye
      p 'bye'
    end

    puts instance_methods(false)
  end
end

# >> hi
# >> bye

当您将false传递给instance_methods时,您会指示它不包含超类的方法。

答案 1 :(得分:2)

我认为您在methodinstance_methods

之间感到困惑
module Test
  class A
    def hi
      p 'hi'
    end

    def bye
      p 'bye'
    end

    puts instance_methods.sort
    p '---------'
    puts instance_methods.sort - Object.instance_methods
  end
end

输出:

[:!, :!=, :!~, :<=>, :==, :===, :=~, :__id__, :__send__, :bye, :class, :clone, :define_singleton_method, :display, :dup, :enum_for, :eql?, :equal?, :extend, :freeze, :frozen?, :hash, :hi, :inspect, :instance_eval, :instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :kind_of?, :method, :methods, :nil?, :object_id, :private_methods, :protected_methods, :public_method, :public_methods, :public_send, :remove_instance_variable, :respond_to?, :send, :singleton_class, :singleton_methods, :taint, :tainted?, :tap, :to_enum, :to_s, :trust, :untaint, :untrust, :untrusted?]
"---------"
[:bye, :hi]