From 8b6defc59c0ba6d108cf8cd0ec2d12b9f6b123ad Mon Sep 17 00:00:00 2001 From: C-Lion Date: Wed, 17 Oct 2018 00:49:52 +0300 Subject: [PATCH] correct formatting of Functions-in-Ruby.md --- Functions-in-Ruby.md | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/Functions-in-Ruby.md b/Functions-in-Ruby.md index f56ad19..a4b483d 100644 --- a/Functions-in-Ruby.md +++ b/Functions-in-Ruby.md @@ -1,20 +1,39 @@ -You can define a function using the reserve word `def` they are commonly methods than return a value +#Functions in Ruby +You define a function using the reserved word `def`on the first line of the function (the function declaration) and using the reserved word `end` on the last line, after all the action is done. + +Ruby Methods always return a value, and always return only one single thing (an object). This object could be the object nil, but it is still an object. + +An option for returning multiple objects is to return an Array that hold the things you need, but the Array itself is also a single object. + +##Basic Examples: -```ruby -def my_function - return "something" -end +``` + def my_function + return "something" + end ``` You can pass arguments that will be used within the method like this -```ruby -def sum(a, b) - return a + b -end +``` + def sum(a, b) + return a + b + end ``` This method return the sum of a plus b arguments +##Return is optional, but... +Use of the return statement is optional in Ruby. However, if not used, the method will return the value that is returned by the last evaluated statement in that method. + +``` + def no_return(number) + number + 2 + end + + p no_return(3) +``` +The function no_return() returns 5 because by default, Ruby methods return the value of the last expression evaluationed in the method. +If you want (or need) to return from a method "early" you can use return statement as usual, but be careful as doing so may result in some code not being executed. \ No newline at end of file