Reputation: 31
I'm trying to create a method to check if three variables a
, b
and c
are a pythagorean triplet. I set it up with a known triplet: 3
, 4
, 5
. This program won't run though and I can't figure out why.
a = 3
b = 4
c = 5
def triplet?
if a**2 + b ** 2 == c ** 2
puts 'pythagorean triplet'
else puts 'not a pythagorean triplet'
end
end
triplet?
It returns the error message:
undefined local variable or method `a' for main:Object (NameError)
Any help will be much appreciated.
Upvotes: 1
Views: 53
Reputation: 62648
a
, b
, and c
are local to the scope they're defined in, and thus aren't visible to separate scopes (such as other methods). See the doc on Object#def:
Starts a new local scope; local variables in existence when the def block is entered are not in scope in the block, and local variables created in the block do not survive beyond the block.
What you want to do is pass numbers as parameters:
def triplet?(a, b, c)
if a**2 + b ** 2 == c ** 2
puts 'pythagorean triplet'
else puts 'not a pythagorean triplet'
end
end
triplet?(3, 4, 5)
This will define those three variables in the scope of the triplet?
method, then you populate their values by passing them when you invoke the method.
A small point of note, by convention, predicate methods (that is, methods ending in ?
) in Ruby conventionally return a boolean. To write this method idiomatically, you might say:
def triplet?(a, b, c)
a**2 + b ** 2 == c ** 2
end
if triplet?(3, 4, 5)
puts 'pythagorean triplet'
else
puts 'not a pythagorean triplet'
end
That way, triplet?
will always return a boolean true or false, then you can use it in your code to write English-y sentences.
Upvotes: 2
Reputation: 6123
a = 3
b = 4
c = 5
def triplet?(a, b, c)
if a**2 + b ** 2 == c ** 2
puts 'pythagorean triplet'
else
puts 'not a pythagorean triplet'
end
end
triplet?(a, b, c)
def
creates a function. Inside the function block, you have a scope. a
, b
, and c
are not in that scope. Tell the function to take parameters a, b, c
and pass it the parameters.
There is no relation between the name you give the function parameters and the function parameters you pass.
The following will also work:
x = 3
y = 4
z = 5
def triplet?(a, b, c)
if a**2 + b ** 2 == c ** 2
puts 'pythagorean triplet'
else
puts 'not a pythagorean triplet'
end
end
triplet?(x, y, z)
Upvotes: 0
Reputation: 168091
Within the definition block, which is the scope for local variables, a
is not defined, hence the error message.
Upvotes: 0