Skip to content

Commit

Permalink
Simplify Enumerable#to_a (#15432)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
straight-shoota authored Feb 10, 2025
1 parent a2573f9 commit e4c904a
Show file tree
Hide file tree
Showing 4 changed files with 3 additions and 16 deletions.
4 changes: 1 addition & 3 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 0 additions & 11 deletions src/indexable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
# ```
Expand Down
2 changes: 1 addition & 1 deletion src/tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit e4c904a

Please sign in to comment.