Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
number
base
conversion
communitycreator

How to convert a number to any number base in Ruby

okwudili onyejiaku

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 numbers
num1 = 10

# convert to different
# bases
a = num1.to_s(2)  # base 2
b = num1.to_s(8)
c = num1.to_s()   # base 10, default
d = num1.to_s(16) # base 16

# print results
puts a  # 1010
puts b  # 12
puts c  # 10
puts d  # a
Convert a number to different number bases in Ruby

Explanation

  • 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.

RELATED TAGS

ruby
number
base
conversion
communitycreator
RELATED COURSES

View all Courses

Keep Exploring