-
-
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
[RFC] Add Int#digits method #8554
Comments
To avoid creating too much overhead I ended up doing Not that I can say I have needed |
I'm sold |
This would be awesome for 128int support |
Is there any reasoning as to not include this in |
Exactly. This wouldn't fit for floating point numbers. |
Random idea: Name the method And also add an iterator |
Implemented in #9383 |
The idea is to have a
digits
method similar to what Ruby has:Why?
The first question that we take into account when considering adding a new method to the standard library is: what's the use case?
Well, my use case, and I guess for others too, is using this method whenever it's needed. In my case it's for today's Advent of Code (day 4).
But wait! That's not a "real world" use case! Or is it...? I think we are solving these fun challenges in the real world, and one of Crystal's goals is to have fun, and it's definitely more fun to have this method than to not have it. Also,
digits
is much faster than doingnumber.to_s.chars.map(&.to_i)
: there's no need to create an intermediate string nor intermediate arrays.Should
123.digits
be[3, 2, 1]
or[1, 2, 3]
?Excellent question!
Ruby returns
[3, 2, 1]
which might not be intuitive but it makes it so that the first digit is 3, the second one is 2, etc. I guess if we look at it like decimal places, in the first place it's the 0-10 range, the second place is the 10-100 range, etc. So it's probably fine. And one can always do123.digits.reverse!
if you want it the other way around, and it is what the method would need to do anyway because of how the array is built (diving and modding by 10).I also think the return type should always be
Array(Int32)
becauseInt32
is the most common type to use, and digits can only be from 0 to 9.There's already #5598 but we could probably start a new PR from scratch.
Thoughts?
(Edit: that's why I also think we should eventually add
String#center
andString#swapcase
: well, the first one is very useful in real world scenarios... the second one probably not, but it's really easy to implement and it's nice when you find it there and it can actually help you solve a problem, be it a challenge or anything else)The text was updated successfully, but these errors were encountered: