0

I wrote a simple program which works:

a = 4.to_s(2) 

puts a.reverse

I want to be able to change it based on input from the user in the terminal. This is what I wrote:

puts 'Please enter a number you would like to see expressed in binary form'

i = gets.chomp

b = i.to_s(2)

puts b

This is the error that I keep getting:

`to_s': wrong number of arguments(1 for 0) (ArgumentError)
2
  • change it means what ? 4 or 2 ? Commented Jun 18, 2014 at 20:03
  • @ArupRakshit, sorry, posted the question before it was finished by accident. it's more complete now. Commented Jun 18, 2014 at 20:04

3 Answers 3

1

You're starting with a string, so you need to convert it:

i.to_i.to_s(2)

The #to_s method on a string doesn't take any arguments.

Sign up to request clarification or add additional context in comments.

Comments

1

You do not need the chomp method, #to_i will take care of it.

Write it as:

puts 'Please enter a number you would like to see expressed in binary form'

i = gets.to_i
b = i.to_s(2)

puts b

You are calling to_s on an string, not on integer as you are thinking, because Kernel#gets always gives you a String object.

First, convert it to Fixnum, then call Fixnum#to_s on the Fixnum instance, which takes an argument, but String#to_s doesn't accept arguments, which was why you got a complaint from Ruby.

1 Comment

thank you for such an through explanation. much appreciated! =)
0

It seems that you want to use Fixnum#to_s but in your program gets.chomp returns a string, so you actually call String#to_s

You can could do:

i = gets.chomp.to_i

3 Comments

Why would you think Fixnum#to_s was redefined?
(6*9).to_s(13) returns "42" which makes this method pretty handy.
It is the ultimate method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.