Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving error with converting variable to binary in ruby with to_s(2)

Tags:

ruby

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?

like image 472
user3468632 Avatar asked Feb 10 '26 08:02

user3468632


2 Answers

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)
like image 148
peter Avatar answered Feb 15 '26 19:02

peter


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
like image 38
Cary Swoveland Avatar answered Feb 15 '26 18:02

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!