Non-decimal radices/Convert: Difference between revisions

→‎{{header|Ruby}}: moved over from Common number base parsing
(→‎{{header|Ruby}}: moved over from Common number base parsing)
Line 649:
Caution: <tt>to_i</tt> simply stops when it reaches an invalid character; it does not raise any exceptions. So sometimes it may appear to parse something and get a result, but it is only based on part of the input string:
<lang ruby>"59".to_i(7) # returns 5, but this is probably not what you wanted</lang>
 
For a general base parsing that raises an exception for invalid characters:
{{trans|Tcl}}
<lang ruby>def scanbase(str, base)
res = 0
digits = %w{0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z}
str.to_s.downcase.each_char do |c|
idx = digits[0,base].find_index(c)
idx.nil? and raise ArgumentError, "invalid base-#{base} digit: #{c}"
res = res * base + idx
end
res
end
 
scanbase 255, 19 # => 822
scanbase dec1, 8 # => ArgumentError: invalid base-8 digit: 9</lang>
 
=={{header|Slate}}==
Anonymous user