Permalink
Browse files

fix #to_s (report from "Andrew Roberts" thanks!!)

  • Loading branch information...
1 parent a329f63 commit b472c51fa1c62105656571ad79e9f60487e03d5e @kachick committed Feb 15, 2012
Showing with 19 additions and 5 deletions.
  1. +7 −1 example.rb
  2. +5 −4 lib/integer/base.rb
  3. +7 −0 test/test_integer-base.rb
View
@@ -22,4 +22,10 @@
p 'a'.to_i(my_chars_2)
p 'a0'.to_i(my_chars_2)
p 'aib'.to_i(my_chars_2)
-p 192.to_s(my_chars_2)
+p 192.to_s(my_chars_2)
+
+my_chars_3 = %w[0 1]
+p 0.to_s(my_chars_3)
+p 1.to_s(my_chars_3)
+p 2.to_s(my_chars_3)
+p 3.to_s(my_chars_3)
View
@@ -46,14 +46,15 @@ def parse(str, chars)
# @return [String]
def convert_to_string(int, chars)
raise TypeError unless int.kind_of? Integer
-
+ return '0' if int == 0
+
chars = base_chars_for chars
base = chars.length
-
+
''.tap do |s|
n = int
-
- while (n, excess = n.divmod base).last > 0
+
+ until (n, excess = n.divmod base; n == 0 && excess == 0)
s << chars[excess]
end
@@ -19,5 +19,12 @@ def test_characterable
def test_to_s
assert_equal('aib', 192.to_s(MY_CHARS))
+ chars_binary = %w[0 1]
+ assert_equal('0', 0.to_s(chars_binary))
+ assert_equal('1', 1.to_s(chars_binary))
+ assert_equal('10', 2.to_s(chars_binary))
+ assert_equal('11', 3.to_s(chars_binary))
+ assert_equal('100', 4.to_s(chars_binary))
+ assert_equal('101', 5.to_s(chars_binary))
end
end

0 comments on commit b472c51

Please sign in to comment.