I'm learning to program in Ruby and I tried to do a basic exercise with arithmetic operations, but I don't understand what happens when displaying and calculating some operations inside a puts
:
puts "Ingrese una variable para realizar la operaciones arítmeticas"
print "El primer valor númerico: "
Y = gets
print "El segundo valor: "
X = gets
puts ("Suma: "+(Y+X).to_s)
puts ("Resta: "+(Y-X).to_s)
puts ("Producto: "+(Y*X).to_s)
puts ("Cociente: "+(Y/X).to_s)
puts ("Resto: "+(Y%X).to_s)
In each of the instructions where I try to display the result, I get a different error for each of the operations, except for addition and remainder (or modulo):
For subtraction:
Ingrese una variable para realizar la operaciones arítmeticas
El primer valor númerico: 4
El segundo valor: 1
Suma: 41Traceback (most recent call last):
./Ejercicio1.rb:7:in `<main>': undefined method `-' for "4":String (NoMethodError)
Did you mean? -@
Product:
Ingrese una variable para realizar la operaciones arítmeticas
El primer valor númerico: 4
El segundo valor: 1
Suma: 41
Traceback (most recent call last):
1: from ./Ejercicio1.rb:8:in `<main>'
./Ejercicio1.rb:8:in `*': no implicit conversion of String into Integer (TypeError)
Quotient:
Ingrese una variable para realizar la operaciones arítmeticas
El primer valor númerico: 4
El segundo valor: 1
Suma: 41
Traceback (most recent call last):
1: from ./Ejercicio1.rb:8:in `<main>'
./Ejercicio1.rb:8:in `*': no implicit conversion of String into Integer (TypeError)
You are trying to add strings, for which only the operations are defined
+
and%
, the rest will throw you an error:What you have to do is convert your string to integer using
gets.to_i