user1663582
user1663582

Reputation: 31

Convert decimal into binary, octal, and hexadecimal?

I am trying to convert a variable, which will always be a number, into binary, octal, and hex with Ruby.

The code I have at this point is:

def convert(number)
  puts "#{number} in decimal is"
  puts "#{number.to_s(2)} in binary"
  puts "#{number.to_s(8)} in octal"
  puts "#{number.to_s(16)} in hexadecimal"
end

and so far the output is:

2 in decimal is
10 in binary
2 in octal
2 in hexadecimal

The first two lines run fine, but after that it is ignoring the conversion command and just putting the variable in. Does anyone have any idea what it is I am missing?

Upvotes: 2

Views: 4237

Answers (1)

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79562

You are missing the fact that 2 is... 2 in base 8, 16, or any base greater than 2. Try convert(42) for fun.

Upvotes: 10

Related Questions