1

The following code to double a number is not working as expected. E.g., if input is 5, it is returning 55 instead of 10.

# program to double a number taken from user input using user defined method    
def double (x)
  puts("Lets yield!")
  yield x * 2
end

puts "Enter number you want to double : "
x = gets.chomp

double (x) { |n| puts n }

2 Answers 2

3

Because you are using the * method on a string. Convert x to an integer.

x = gets.chomp.to_i
Sign up to request clarification or add additional context in comments.

6 Comments

i am not putting 5 as a string... I am giving input as a number .
When you use gets.chomp you always have a string
add puts x.class after that line
@user8567677 why would you need chomp then? A number cannot contain a newline, can it?
@user8567677 A string can contain only digits, and still be a string! 123 is an Integer; "456" is a String. gets will always interpret the input as a String.
|
0

According to this previous question, We take input using gets but it causes a problem of taking \n as a part of the input at the end of the string for example:

x=gets #Enter amr as input then it will print 4, three chars + \n
print x.length 

here came gets.chomp which gets rid of \n in the end, So both gets and gets.chomp take the input as a string so you need to convert it as @Ursus mentioned before by using gets.chomp.to_i

Comments

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.