user8567677
user8567677

Reputation: 11

Number multiplication in Ruby returning string concatenation instead of integer product

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 }

Upvotes: 1

Views: 161

Answers (2)

Amro Abdalla
Amro Abdalla

Reputation: 584

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

Upvotes: 0

Ursus
Ursus

Reputation: 30056

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

x = gets.chomp.to_i

Upvotes: 3

Related Questions