# ¿Por qué obtengo "Variable local indefinida" en la calculadora del Teorema de Pitágoras?

I made a Pythagorean Theorem calculator in Ruby and it has a bug/does not run. The error is:

``````undefined local variable or method `a2'
``````

Me preguntaba si alguien podría ayudar.

``````puts "Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle."
a = gets.to_f
b = gets.to_f
a**2 == a2
b**2 == b2
a2 + b2 = a2_b2
puts "The hypotenuse of your triangle is: #{ Math.sqrt(a2_b2)}"
``````

preguntado el 10 de septiembre de 13 a las 00:09

## 2 Respuestas

You just had two small errors:

``````puts "Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle."
a = gets.to_f
b = gets.to_f
a2 = a**2
b2 = b**2
a2_b2 = a2 + b2
puts "The hypotenuse of your triangle is: #{ Math.sqrt(a2_b2)}"
``````

--

``````Welcome to my pythagorean theorem calculator. This calculator can find the hypotenuse of any right triangle. Please enter side A of your triangle.
3
4
The hypotenuse of your triangle is: 5.0
``````

Respondido el 10 de Septiembre de 13 a las 00:09

You are confusing assignment with the equality operator (`==`). When you declare:

``````a**2 == a2
``````

you are asking Ruby whether a2 is equal to the value of the a2 variable, which is undefined in your example code. You can see this same error at work if you open a new Ruby console and enter a2 without a program:

``````irb(main):001:0> a2
NameError: undefined local variable or method `a2' for main:Object
from (irb):1
from /usr/bin/irb:12:in `<main>'
``````

## Some Refactoring

While you can fix your code by ensuring that you assign values to variables before you reference them, you should probably make your code more idiomatic. As an example, consider the following:

``````# In the console, paste one stanza at a time to avoid confusing the REPL
# with standard input.

print 'a: '
a = Float(gets)

print 'b: '
b = Float(gets)

c_squared  = a**2 + b**2
hypotenuse = Math.sqrt(c_squared)
``````

Respondido el 10 de Septiembre de 13 a las 00:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.