鉴于
class Bird
def self.bird_ancestors
ancestors.first(ancestors.find_index(Bird)+1)
end
end
class Duck < Bird
end
class FeatheredDuck < Duck
end
FeatheredDuck.bird_ancestors => [FeatheredDuck,Duck,Bird]
Duck.bird_ancestors => [Duck,Bird]
Bird.bird_ancestors => [Bird]
如何在Bird
内引用Bird
而不明确?我知道self
和__class__ doesnt
有效。
答案 0 :(得分:2)
在类方法中,self
引用当前的类对象:
class Bird
def self.foo
self
end
end
p Bird.foo # => "Bird"
答案 1 :(得分:1)
这样做:
class Bird
def self.bird_ancestors
ancestors.take_while { |c| c.respond_to? __method__ }
end
end
class Duck < Bird
end
class FeatheredDuck < Duck
end
FeatheredDuck.bird_ancestors #=> [FeatheredDuck, Duck, Bird]
Duck.bird_ancestors #=> [Duck, Bird]
Bird.bird_ancestors #=> [Bird]
select
也有效,但take_while
(由@Aditya建议)更好,因为一旦从块中返回ancestors
,它就会停止搜索false
。
答案 2 :(得分:0)
你可以这样做:
class Bird
def self.bird_ancestors
class_name = method(__method__).owner.to_s.gsub(/#<Class:|>/,'')
ancestors.first(ancestors.map{|x| x.to_s}.find_index(class_name)+1)
end
end
(__method__ is the current method)