Skip to content

Commit 6769f36

Browse files
committed
Add collection querying rule
1 parent 38a8961 commit 6769f36

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.adoc

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4690,6 +4690,37 @@ 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: Predicate methods without arguments aren't applicable when collection includes falsy values (e.g. `[nil, false].any?` evaluates to `false`).
4723+
46934724
== Numbers
46944725

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

0 commit comments

Comments
 (0)