From e4c904a92cd7e67b295e10c178bdbe6637679056 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Mon, 10 Feb 2025 12:00:25 +0100 Subject: [PATCH] Simplify `Enumerable#to_a` (#15432) The implementation of `#to_a` is identical to the yielding variant `#to_a(&)`. We can simply delegate to `#to_a(&)`. As a bonus, inheriting types which override `#to_a(&)` with an optimized implementation will implicitly use the same optimization for `#to_a` as well. This means we can drop `Indexable#to_a`. Inheriting types `Tuple` and `Hash` already explicitly delegate `#to_a` to their override implementations of `#to_a(&)`. We keep these overrides of `#to_a` because they augment the documentation. But we replace the method bodies with `super` to make it clear that the behaviour is inherited and the `def` only provides documentation. --- src/enumerable.cr | 4 +--- src/hash.cr | 2 +- src/indexable.cr | 11 ----------- src/tuple.cr | 2 +- 4 files changed, 3 insertions(+), 16 deletions(-) diff --git a/src/enumerable.cr b/src/enumerable.cr index 0993f38bbc4d..9fcba66ddf3a 100644 --- a/src/enumerable.cr +++ b/src/enumerable.cr @@ -2013,9 +2013,7 @@ module Enumerable(T) # (1..5).to_a # => [1, 2, 3, 4, 5] # ``` def to_a : Array(T) - ary = [] of T - each { |e| ary << e } - ary + to_a(&.as(T)) end # Returns an `Array` with the results of running *block* against each element of the collection. diff --git a/src/hash.cr b/src/hash.cr index 1be6543d730c..c145bda36309 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -2083,7 +2083,7 @@ class Hash(K, V) # # The order of the array follows the order the keys were inserted in the Hash. def to_a : Array({K, V}) - to_a(&.itself) + super end # Returns an `Array` with the results of running *block* against tuples with key and values diff --git a/src/indexable.cr b/src/indexable.cr index 4a3990e83870..3f6dca1762b1 100644 --- a/src/indexable.cr +++ b/src/indexable.cr @@ -693,17 +693,6 @@ module Indexable(T) end end - # Returns an `Array` with all the elements in the collection. - # - # ``` - # {1, 2, 3}.to_a # => [1, 2, 3] - # ``` - def to_a : Array(T) - ary = Array(T).new(size) - each { |e| ary << e } - ary - end - # Returns an `Array` with the results of running *block* against each element of the collection. # # ``` diff --git a/src/tuple.cr b/src/tuple.cr index a658e36774c7..a8dd3a040727 100644 --- a/src/tuple.cr +++ b/src/tuple.cr @@ -545,7 +545,7 @@ struct Tuple # {1, 2, 3, 4, 5}.to_a # => [1, 2, 3, 4, 5] # ``` def to_a : Array(Union(*T)) - to_a(&.as(Union(*T))) + super end # Returns an `Array` with the results of running *block* against each element of the tuple.