How to Convert an Octal String to an Integer in Ruby?

In Ruby, you can use the Kernel#Integer method or the String#to_i method to convert an octal string to its integer equivalent. For example, you can do the following:

Convert Octal String With the 0x Radix Indicator

If an octal string is prefixed with the "0o" (or "0O") octal radix prefix, then only for the String#to_i method you need to specify the numeric base of 8 because the Kernel#Integer method automatically converts strings with radix indicators. For example:

puts "0o30071".to_i(8) #=> 12345

puts Integer("0o30071") #=> 12345

If you don't specify the numeric base for the String#to_i method, then it would return 0:

puts "0o30071".to_i #=> 0

This is because the String#to_i method only interprets leading characters as numbers in a string (which in this case is 0), and ignores characters beyond the end of a valid number.

Convert Octal String Without a Radix Indicator

If the octal string is not prefixed with "0o" (or "0O") octal radix prefix, then you must specify the numeric base of 8 to both methods (i.e. Kernel#Integer and String#to_i), for example, like so:

puts "0o30071".to_i(8) #=> 12345

puts Integer("0o30071", 8) #=> 12345

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.