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.
num.to_s(base)
num
: This is the number that we want to convert.
base
: This is the base to which we want to convert num
.
The returned value is equivalent to the number num
, but in the specified base that is passed to the to_s()
method.
# 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
Line 2: We create a number value 10
.
Line 6: We call to_s
to convert the number to a number in base-2.
Line 7: We call to_s
to convert the number to a number in base-8.
Line 8: We call to_s
to 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_s
to convert the number to a number in base-16.
Lines 12–15: We print the results to the console.