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
2 番目puts
は何も出力せず、最初のものは 'hi' と 'bye' を出力しません。なんで?
どちらの行もA
クラス自体のスコープで実行されるため、 whilehi
と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
、スーパー クラスのメソッドを含めないように指示します。
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]