user2620747
user2620747

Reputation: 21

Multiplication in Ruby

I am trying to multiple a variable (input from the user) and 4. For some reason, this simple task can not be completed by me.

Here is the code:

print "Enter an Integer between 1 and 12: "
x = gets
puts x * 4

Instead of multiplying x and 4, it will print x a total of four times.

Upvotes: 1

Views: 2831

Answers (1)

Paul Prestidge
Paul Prestidge

Reputation: 1127

That's because x is a string, and the * method on strings is repetition. You need to convert it to a number using the #to_i method first.

x = gets.to_i
puts x * 4

Should do what you want.

Upvotes: 3

Related Questions