#Return
Return - All methods have a return object which will be different than the output.
Once an object is returned in a method the method breaks. Nothing below the return statement will run.
Return can only return one object. If you need to return more than one object stick them in an array which is considered one object.
def linear_search(roster, name)
roster.each_with_index do |student, i|
if student.first_name == name
return i #If we get to this we will exit the method.
end
end
return -1 #We will get to this only if we don't return above.
end # linear search
def add_and_subtract(n1=0, n2=0)
add = n1 + n2
sub = n1 - n2
return [add, sub] #The []s are optional as return will return an array anyway.
end
- Methods have a default return value; the last operation's return value.
- Return will both return a value and exit the method.
- Returning a value and using puts outside a method can provide more flexibility than using puts inside.
- Return is especially useful with conditional statements.
- Methods can only return one object, use an array to return more.