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'。为什么呢?
答案 0 :(得分:5)
因为这两行都是在A
类本身的范围内执行的,而hi
和bye
是该类的实例方法。试试这个:
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)
我认为您在method
和instance_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]