Tutorial 9 : Functions
Definition of the functions
To define functions we is to type def to define function and the give a space and write the name of the functions then in braces pass the parameters if any. If no so give only open and close braces and then if you want to return the value or not. If you want to return a value so type return and then type to which is to be return if it is string type .to_s and if it is integer so type .to_i
For example of a function of addition of two numbers we can write it like this
Input Output
In this the function is called by value 3 and 4 by which it return and give the output 7
Change the value under a function
This part of tutorial is to understand that when the value of an integer get changes and when it takes new values. So check this program and try to understand.
Input Output
In first line we give the value of x to 1 and after that we create function of change_x and pass the value of x and third line and we change thw value of x from 1 to 4. and in 5th line we end the function and in 6th line we call the function by the name and in 7th line we print the value of x
Any value change inside the function will remain in the function it will not affect the outside. It is so important when you work on the functions.
Exceptions
We can catch exception by both catch and rescue
Input Output
In this program we are catching the exceptions by rescue function here we are saying that rescue all the conditions when user want to divide his number by zero.
No comments:
Post a Comment