简体   繁体   English

为什么instance_methods(false)返回祖先方法?

[英]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?

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. 在这种情况下, AB在其各自的级别上都有一个实例方法:foo ,因此它们都将在已实现实例方法的列表中返回:foo

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. 我相信您认为错误地出现在此列表中的大多数方法在FloatNumeric以不同的实现方式得到了类似的实现。 Probably to handle the case where or both of the operands is a Float . 可能处理两个操作数或两个操作数均为Float

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM