Skip to content

Commit f1e6d6b

Browse files
committed
[GR-18163] Fix Integer#digits to handle more bases
PullRequest: truffleruby/2335
2 parents b0b25af + c772179 commit f1e6d6b

File tree

4 files changed

+21
-4
lines changed

4 files changed

+21
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ Compatibility:
3939
* Switched to the io-console C extension from C ruby for better performance and compatibility in `irb`.
4040
* Coerce the message to a `String` for `BasicSocket#send` (#2209, @HoneyryderChuck).
4141
* Support buffer argument for `UDPSocket#recvfrom_nonblock` (#2209, @HoneyryderChuck).
42+
* Fixed `Integer#digits` implementation to handle more bases (#2224, #2225).
4243

4344
Performance:
4445

spec/ruby/core/integer/digits_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,13 @@
2929
it "raises Math::DomainError when calling digits on a negative number" do
3030
-> { -12345.digits(7) }.should raise_error(Math::DomainError)
3131
end
32+
33+
it "returns integer values > 9 when base is above 10" do
34+
1234.digits(16).should == [2, 13, 4]
35+
end
36+
37+
it "can be used with base > 37" do
38+
1234.digits(100).should == [34, 12]
39+
980099.digits(100).should == [99, 0, 98]
40+
end
3241
end

src/main/ruby/truffleruby/core/integer.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -314,8 +314,17 @@ def pred
314314
def digits(base = 10)
315315
raise Math::DomainError, 'out of domain' if negative?
316316
base = Primitive.rb_to_int(base)
317-
318-
to_s(base).chars.map(&:to_i).reverse
317+
raise ArgumentError, 'negative radix' if base < 0
318+
raise ArgumentError, "invalid radix #{base}" if base < 2
319+
return [0] if self == 0
320+
321+
result = []
322+
x = self
323+
while x > 0
324+
result << x % base
325+
x /= base
326+
end
327+
result
319328
end
320329

321330
def self.sqrt(n)

test/mri/excludes/TestInteger.rb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
exclude :test_Integer, "needs investigation"
2-
exclude :test_digits_for_non_integral_base_numbers, "needs investigation"
32
exclude :test_round, "needs investigation"
43
exclude :test_square_root, "needs investigation"
54
exclude :test_Integer_with_exception_keyword, "needs investigation"
65
exclude :test_bitwise_and_with_integer_coercion, "needs investigation"
76
exclude :test_bitwise_or_with_integer_coercion, "needs investigation"
87
exclude :test_bitwise_xor_with_integer_coercion, "needs investigation"
98
exclude :test_ceil, "needs investigation"
10-
exclude :test_digits, "needs investigation"
119
exclude :test_floor, "needs investigation"
1210
exclude :test_pow, "needs investigation"
1311
exclude :test_truncate, "needs investigation"

0 commit comments

Comments
 (0)