How to convert a number to any number base in Ruby
Overview
In Ruby, we can convert any number to any base using the method to_s(). This method requires a parameter that is between 2 and 36. This means we can convert any number to any base from base-2 to base-36.
If no parameter is passed, then the number will be converted to a base-10 value.
Syntax
num.to_s(base)
Parameters
num: This is the number that we want to convert.
base: This is the base to which we want to convert num.
Return value
The returned value is equivalent to the number num, but in the specified base that is passed to the to_s() method.
Example
# create some numbersnum1 = 10# convert to different# basesa = num1.to_s(2) # base 2b = num1.to_s(8)c = num1.to_s() # base 10, defaultd = num1.to_s(16) # base 16# print resultsputs a # 1010puts b # 12puts c # 10puts d # a
Explanation
-
Line 2: We create a number value
10. -
Line 6: We call
to_sto convert the number to a number in base-2. -
Line 7: We call
to_sto convert the number to a number in base-8. -
Line 8: We call
to_sto convert the number to a number in base-10. Notice that we didn’t pass any parameter to the method. It will convert it to base 10 by default. -
Line 9: We call
to_sto convert the number to a number in base-16. -
Lines 12–15: We print the results to the console.