Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

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)

And local information


Properties (only for methods connected to instantiated objects) (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 .

Hint: search for % operator

Assignment 2: How to start?


Create a program that calculates the first 10 prime numbers: 1, 3, 5, 7, 11, 13, 17, 19, 23 Modify the program to pass this 10 as a parameter Check that it works when you introduce a value different than 10

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

You might also like