Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Array#insert_all #14486

Merged

Conversation

summer-alice
Copy link
Contributor

This adds a method to Array that allows you to insert all elements from one array into another at a given index.

While this is already possible in Crystal using range assignment, the syntax and side effects may not be immediately obvious. Achieving the desired behaviour can also be error-prone as it depends on the number of dots used.

arr = [1, 2, 6]
# arr[2..2] = [3, 4, 5]   # => [1, 2, 3, 4, 5]
arr[2...2] = [3, 4, 5]    # => [1, 2, 3, 4, 5, 6]

The new method would simplify it to:

arr = [1, 2, 6]
arr.insert_all(2, [3, 4, 5]) # => [1, 2, 3, 4, 5, 6]

(For further reference I did create a post on the forum)

This method inserts all elements from a specified Enumerable or Iterable
in to the Array at a specified index, moving any subsequent elements to
the right.
The implementations of #insert_elements_at are almost the same, with the
addition of an 'index' parameter, which for #concat is always the size
of the array.
src/array.cr Outdated Show resolved Hide resolved
src/array.cr Outdated Show resolved Hide resolved
src/array.cr Outdated Show resolved Hide resolved
src/array.cr Show resolved Hide resolved
spec/std/array_spec.cr Outdated Show resolved Hide resolved
spec/std/array_spec.cr Outdated Show resolved Hide resolved
summer-alice and others added 2 commits April 17, 2024 19:16
Co-authored-by: Johannes Müller <straightshoota@gmail.com>
@straight-shoota straight-shoota added this to the 1.13.0 milestone Jun 10, 2024
@straight-shoota straight-shoota merged commit 2d71e35 into crystal-lang:master Jun 11, 2024
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants