Actions
Feature #12447
closedInteger#digits for extracting digits of place-value notation in any base
Description
I sometimes want to extract digits of place-value notation of integer numbers.
For example:
12345.digits #=> [5, 4, 3, 2, 1]
12345.digits(100) #=> [45, 23, 1]
One typical use case is calculating checksum digit.
I found some code extracting digits by the way like int.to_s.chars.map(&:to_i)
.
- https://github.com/joeljunstrom/ruby_luhn/blob/master/lib/luhn.rb#L43
- https://github.com/elitwin/check_digit/blob/master/lib/check_digit/damm.rb#L28
- https://github.com/elitwin/check_digit/blob/master/lib/check_digit/luhn.rb#L14
- https://github.com/elitwin/check_digit/blob/master/lib/check_digit/verhoeff.rb#L42
Introducing Integer#digits can reduce needless string allocation in such cases.
The patch was pushed into the repository in github.
https://github.com/mrkn/ruby/commit/5dce32d
Updated by mrkn (Kenta Murata) over 8 years ago
- Related to Feature #4787: Integer#each_modulo(n) added
Updated by mrkn (Kenta Murata) over 8 years ago
- Related to Feature #12116: `Fixnum#divmod`, `Bignum#divmod` with multiple arguments added
Updated by mrkn (Kenta Murata) over 8 years ago
- Description updated (diff)
Updated by mrkn (Kenta Murata) over 8 years ago
- Description updated (diff)
Updated by matz (Yukihiro Matsumoto) over 8 years ago
Approved.
Matz.
Updated by akr (Akira Tanaka) over 8 years ago
I wanted such method to encode integer in some binary format.
(I cannot remember concrete example.)
For example, pack("w") can be implementd using Integer#digits.
Updated by mrkn (Kenta Murata) over 8 years ago
Summary of decision in today's Developer meeting:
- The results endian is little endian.
- Raise
Math::DomainError
for negative receiver. - Return
[0]
for0
.
Updated by mrkn (Kenta Murata) over 8 years ago
- Status changed from Open to Closed
Updated by shyouhei (Shyouhei Urabe) over 5 years ago
- Related to Feature #16011: Digit grouping added
Actions
Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0