Class: Integer

Provides support for converting integers to Strings, and back again. The strings are structured so that lexicographic sorting order is preserved.

That is, if integer1 is less than integer2 for any two integers integer1 and integer2, then integer1.to_s_lex is lexicographically less than integer2.to_s_lex. (Similarly for "greater than" and "equals".)

This class handles numbers between - 10 ** 10,000 and 10 ** 10,000 which should cover all practical numbers. If you need bigger numbers, increase Integer::LEN_STR_SIZE.

Constants

NameValue
LEN_STR_SIZE 4
NEG_LEN_MASK 10 ** LEN_STR_SIZE
LEN_STR_TEMPLATE "%0#{LEN_STR_SIZE}d"

Public Instance Methods


to_s_lex ()

Convert the number to a lexicographically sortable string. This string will use printable characters only but will not be human readable.

    # File lib/ferret/number_tools.rb, line 35
35:   def to_s_lex
36:     if (self >= 0)
37:       num_str = self.to_s
38:       len_str = LEN_STR_TEMPLATE % num_str.size
39:       return len_str + num_str
40:     else
41:       num = self * -1
42:       num_str = num.to_s
43:       num_len = num_str.size
44:       len_str = LEN_STR_TEMPLATE % (NEG_LEN_MASK - num_len)
45:       num = (10 ** num_str.size) - num
46:       return "-#{len_str}%0#{num_len}d" % num
47:     end
48:   end

to_s_pad (width = 10)

Convert the number to a lexicographically sortable string by padding with 0s. You should make sure that you set the width to a number large enough to accommodate all possible values. Also note that this method will not work with negative numbers. That is negative numbers will sort in the opposite direction as positive numbers. If you have very large numbers or a mix of positive and negative numbers you should use the Integer#to_s_lex method

width:number of characters in the string returned. Default is 10. So 123.to_s_pad(5) => 00123 and -123.to_s_pad(5) => -0123
return:padding string representation of the number.
    # File lib/ferret/number_tools.rb, line 60
60:   def to_s_pad(width = 10)
61:     "%#{width}d" % self
62:   end