Functions, Methods, Parameters in Ruby
Functions, Methods, Parameters in Ruby
Method / function
May be associated with class When you define a method not associated with a specific class you can use it in your code without instantiating an object Method needs to be defined Method can be called to use it
Return values
All methods return last evaluated statement
Test1 returns 10, test2 returns 19
def test1
i=9 j = 10 end def test2 i=9 j = 10 return i+j end
Parameters
Used to input information to be used by the method at the time of call Defined in a parameter-list The order is important The variables of the parameters are only visible within the method
Methods do
Transform input (if any)
From the parameter-list during call
To output
Return (brings value back calling surrounding) (optional)
Changing in
Files (optional) Global variables (optional)
Class exercise
Live coding! Recursive methods
Assignment 1
Create and call a function or method that creates returns the fibonacci number of a position Example: Fibonacci(2) -> 1 Fibonacci(5) -> 5 Hand in both the recursive and non-recursive code
Assignment 2
Create and call a function or method that calculates the n-th prime number
First prime number 2 Second prime number 3 Third prime number 5 .
Feeling bored?
The challenge of the week: palindroms 1. Learn what a palindrom is 2. Find funny palindroms 3. Create a recursive method that will check if a word/sentence is a palindrom Hint: a = "hola puts a[0,1] -> h