-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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 Range#clamp
#10148
Comments
We can follow the same rules as ## inclusive ranges
(-5..5).to_a & (0..100).to_a # => [0, 1, 2, 3, 4, 5]
(-5..5).to_a & (-100..100).to_a # => [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
## exclusive ranges
(-5...5).to_a & (-100...0).to_a # => [-5, -4, -3, -2, -1]
## exclusive and inclusive ranges
(-5..5).to_a & (-10...2).to_a # => [-5, -4, -3, -2, -1, 0, 1]
(-5...5).to_a & (-10..2).to_a # => [-5, -4, -3, -2, -1, 0, 1, 2] Some differences: |
Literally just had a use-case for this and searched for it in the docs. +1 :) |
|
Agree - I think it makes sense to close this issue with that PR or create an alias for |
Range isn't
Comparable
, but it could very well define a#clamp
method. The result would be the intersection of both ranges.This method could also be called
#intersect
or#&
, but IMO#clamp
fit's best because it closely resemblesComparable#clamp
.There are a few cases where the expected results may be up for discussion:
(-5..5).clamp(-10...2)
and(-5...5).clamp(-10..2)
) should probably have the same result as if both ranges were exclusive.(-5..5).clamp(10..100)
), the result should probably be an empty range. This can be expressed as an exclusive range with identical begin and end (x...x
). But what shouldx
be? Probably best to use the begin of the clamped range (-5...-5
).-5..5.clamp(10..-10)
), we could try to sort things out, but I suppose it's probably better to just treat them as disparate and return an empty range.The text was updated successfully, but these errors were encountered: