Skip to content

Commit 173ff46

Browse files
committed
Add collection querying rule
1 parent 38a8961 commit 173ff46

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

README.adoc

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4690,6 +4690,54 @@ ary[..42]
46904690
ary[0..42]
46914691
----
46924692

4693+
=== Collection querying [[collection-querying]]
4694+
4695+
When possible, use https://docs.ruby-lang.org/en/master/Enumerable.html#module-Enumerable-label-Methods+for+Querying[predicate methods from `Enumerable`] rather than expressions with `#count`, `#length` or `#size`.
4696+
4697+
Querying methods express the intention more clearly and are more performant in some cases. For example, `articles.any?(&:published?)` is more readable than `articles.count(&:published?) > 0` and also more performant because `#any?` stops execution as soon as the first published article is found, while `#count` traverses the whole collection.
4698+
4699+
[source,ruby]
4700+
----
4701+
# bad
4702+
array.count > 0
4703+
array.length > 0
4704+
array.size > 0
4705+
4706+
array.count(&:something).positive?
4707+
4708+
array.count(&:something) == 0
4709+
4710+
array.count(&:something) == 1
4711+
4712+
# good
4713+
array.any?
4714+
4715+
array.any?(&:something)
4716+
4717+
array.none?(&:something)
4718+
4719+
array.one?(&:something)
4720+
----
4721+
4722+
[NOTE]
4723+
--
4724+
Predicate methods without arguments can't replace `count` expressions when collection includes falsey values:
4725+
[source,ruby]
4726+
----
4727+
[nil, false].any?
4728+
# => false
4729+
4730+
[nil, false].none?
4731+
# => true
4732+
4733+
[nil].one?
4734+
# => false
4735+
4736+
[false].one?
4737+
# => false
4738+
----
4739+
--
4740+
46934741
== Numbers
46944742

46954743
=== Underscores in Numerics [[underscores-in-numerics]]

0 commit comments

Comments
 (0)