Ruby 3.1 adds Class#descendants
source link: https://blog.saeloun.com/2021/12/22/ruby-3.1-adds-class-descendants
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
We often land on a situation where we want to know all the classes which have been inherited from a given class; One such scenario can be while using Single Table Inheritance in Rails.
Here, we might want to identify those classes that are derived from a class.
Rails ~> 3.0
already has such a feature provided
by ActiveSupport
Class#descendants.
To cater to such requirements in Ruby,
Ruby 3.1 introduced Class#descendants
that returns
an array of classes
directly or indirectly inheriting from the receiver, without
including the receiver or singleton classes.
Before
We can implement Class#descendants
using the code
snippet given below-
class Animal
def self.descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
class Mammal < Animal; end
class Dolphin < Mammal; end
class Bat < Mammal; end
class Reptile < Animal; end
class Crocodile < Reptile; end
Animal.descendants
=> [Reptile, Bat, Crocodile, Dolphin, Mammal]
Mammal.descendants
=> [Bat, Dolphin]
Reptile.descendants
=> [Crocodile]
After
class Animal; end
class Mammal < Animal; end
class Dolphin < Mammal; end
class Bat < Mammal; end
class Reptile < Animal; end
class Crocodile < Reptile; end
Animal.descendants
=> [Reptile, Crocodile, Mammal, Bat, Dolphin]
Mammal.descendants
=> [Bat, Dolphin]
Reptile.descendants
=> [Crocodile]
For more discussion related to this change, please refer to this PR.
Recommend
-
61
solidot新版网站常见问题,请点击这里查看。 提交文章 ...
-
69
Don't Step on a Rake, Use Rake::DSL — A look at how Rake, Ruby’s general purpose make-like task runner, operates and how to define tasks outside...
-
15
Ruby adds instance method #except to Hash. This method returns a new hash, which includes everything from the original hash except the given keys. Before...
-
7
Ruby 3.1 adds Array#intersect? method May 18, 2021 , by Alkesh Ghorpade 1 minute read When dealing with Arrays in Ruby we fr...
-
5
Ruby 3.1 adds Enumerable#compact and Enumerator::Lazy#compact Jun 15, 2021 , by Keshav Biswa 2 minute read
-
2
Ruby 3.1 adds MatchData#match and MatchData#match_length Nov 24, 2021 , by Alkesh Ghorpade 1 minute read When working with s...
-
2
Conversation Copy link Member
-
2
Ruby 3.1 adds Class#subclasses Jan 11, 2022 , by Agnidipta Bhattacharjee 1 minute read We often c...
-
7
Ruby 3.1 adds error highlighting gem Feb 16, 2022 , by Alkesh Ghorpade 2 minute read When working wi...
-
5
ruby3 Published on 22 June 2022 ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK