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

Style guide: misleading description for "Slicing with Ranges" #953

Open
ak-lilw opened this issue Nov 21, 2024 · 0 comments
Open

Style guide: misleading description for "Slicing with Ranges" #953

ak-lilw opened this issue Nov 21, 2024 · 0 comments

Comments

@ak-lilw
Copy link

ak-lilw commented Nov 21, 2024

In the style guide under Slicing with Ranges it's said that

[0..-1] in ary[0..-1] is redundant and simply synonymous with ary.

However, one makes a shallow copy while the other doesn't:

ary = [1, 2, 3]
with_slice = ary[0..-1]
without_slice = ary
ary[0] = :changed

# [1, 2, 3]
puts with_slice.inspect

# [:changed, 2, 3]
puts without_slice.inspect

By analogy to the Python idiom ary[:], I would guess that the "bad" form is often written specifically to make a copy rather than an alias.

I suggest that the advice be changed to say something like ary.clone, ary.dup or [*ary] is preferred (whatever is considered better style), or that simply ary is preferred if a copy isn't needed. If clone is a good alternative then it's worth adding that it isn't exactly synonymous with a full slice, since even ary.clone(freeze: false) clones the singleton class, whereas slicing doesn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant