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 }
Uwe
  • 41,420
  • 11
  • 90
  • 134

2 Answers2

3

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

x = gets.chomp.to_i
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • i am not putting 5 as a string... I am giving input as a number . – user8567677 Sep 10 '17 at 16:43
  • When you use `gets.chomp` you always have a string – Ursus Sep 10 '17 at 16:44
  • add `puts x.class` after that line – Ursus Sep 10 '17 at 16:46
  • 2
    @user8567677 why would you need `chomp` then? A number cannot contain a newline, can it? – Stefan Sep 10 '17 at 17:17
  • @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`](https://ruby-doc.org/core/IO.html#method-i-gets). – Tom Lord Sep 10 '17 at 18:34
  • ...And if you look at [the ruby docs for `String`](https://ruby-doc.org/core/String.html#method-i-2A), you'll see that `String * Integer` returns a repeated `String`. – Tom Lord Sep 10 '17 at 18:35
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

Amr Adel
  • 574
  • 1
  • 7
  • 18