Skip to content

Instantly share code, notes, and snippets.

@MilanGrubnic70
Last active August 29, 2015 14:00
Show Gist options
  • Save MilanGrubnic70/11102237 to your computer and use it in GitHub Desktop.
Save MilanGrubnic70/11102237 to your computer and use it in GitHub Desktop.
Return

#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
  1. Methods have a default return value; the last operation's return value.
  2. Return will both return a value and exit the method.
  3. Returning a value and using puts outside a method can provide more flexibility than using puts inside.
  4. Return is especially useful with conditional statements.
  5. Methods can only return one object, use an array to return more.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment