I'm trying to convert a string into a binary:
puts "Tell me a number:"
num1 = gets
puts "The number you gave in binary is " + num1.to_s(2)
But I get a "wrong number of arguments (1 to 0)" error.
Any suggestion on how to proceed?
You need to convert the string you get to a number first
puts "The number you gave in binary is " + num1.to_i.to_s(2)
The simplest way is to use Kernel#sprintf with the b field type.
sprintf("%b", gets)
For example,
sprintf("%b", "34\n")
#=> "100010"
This can also be written
"%b" % gets
You could therefore write the following.
puts "Tell me a number:"
puts "The number you gave in binary is %b" % gets
If the user entered "34\n" this would print
The number you gave in binary is 100010
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With