Kiwi
Kiwi

Reputation: 1093

Why does instance_methods(false) return ancestor methods?

Running this code prints two lists of methods which are not the same size. Why is that?

puts 'Subtracting ancestor methods:'
puts (Float.instance_methods - Object.instance_methods - Numeric.instance_methods).sort
puts
puts 'Requesting no ancestor methods:'
puts Float.instance_methods(false).sort

Subtracting ancestor methods:

*
**
+
-
/
finite?
infinite?
nan?
rationalize
to_f
to_i
to_r

Requesting no ancestor methods:

%
*
**
+
-
-@
/
<
<=
<=>
==
===
>
>=
abs
angle
arg
ceil
coerce
denominator
divmod
eql?
fdiv
finite?
floor
hash
infinite?
inspect
magnitude
modulo
nan?
numerator
phase
quo
rationalize
round
to_f
to_i
to_int
to_r
to_s
truncate
zero?

Upvotes: 1

Views: 54

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187134

I think you are not taking into account overridden methods.

class A
  def foo
    'A'
  end

  def bar
    'baz'
  end
end

class B < A
  def foo
    super + 'B'
  end
end

A.instance_methods(false) #=> [:foo, :bar]
B.instance_methods(false) #=> [:foo]

In this case both A and B have an instance method :foo at their own level, so they would both return :foo in their list of implemented instance methods.

I believe most of the methods that you believe have erroneously appeared in this list are similarly implemented in both Float and in Numeric with varying implementations. Probably to handle the case where or both of the operands is a Float.

Upvotes: 5

Related Questions