Reputation: 1102
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
The second puts
does not print anything, the first one does not print 'hi' and 'bye'. Why?
Upvotes: 1
Views: 686
Reputation: 118271
I think you confused yourself between method
and 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
Output:
[:!, :!=, :!~, :<=>, :==, :===, :=~, :__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]
Upvotes: 2
Reputation: 230336
Because both lines are executed in scope of A
class itself, while hi
and bye
are instance methods of that class. Try this:
module Test
class A
def hi
p 'hi'
end
def bye
p 'bye'
end
puts instance_methods(false)
end
end
# >> hi
# >> bye
When you pass false
to instance_methods
, you instruct it to not include methods of super classes.
Upvotes: 6