我试图为给定的类创建一个包含所有超类的数组。我试着用循环来解决这个问题。为什么这不起作用?

class Object
  def superclasses
    array = []
    klass = self.superclass
    unless klass == nil
      array << klass
      klass = klass.superclass
    end
    array
  end
end

class Bar
end

class Foo < Bar
end

p Foo.superclasses  # should be [Bar, Object, BasicObject]

最佳答案

unless不是循环。你要找的是:

class Object
  def superclasses
    array = []
    klass = self.superclass
    until klass == nil
      array << klass
      klass = klass.superclass
    end
    array
  end
end

class Bar
end

class Foo < Bar
end

p Foo.superclasses # Prints "[Bar, Object, BasicObject]"

此外,你不需要一个新的方法。已经有一个名为until的方法,它基本上满足了您的需求:
class Bar
end

class Foo < Bar
end

p Foo.ancestors # Prints "[Foo, Bar, Object, Kernel, BasicObject]"

注意,Module#ancestors的返回值包括ancestors本身,以及继承链中包含的模块,如Foo。如果不需要,可以这样定义Kernel
class Module
  def superclasses
    ancestors[1..-1].select{|mod| mod.is_a? Class }
  end
end

class Bar
end

class Foo < Bar
end

p Foo.superclasses # Prints "[Bar, Object, BasicObject]"

关于ruby - 为特定类创建父类(super class)数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28114240/

10-12 02:11