Functions are a little bit more complicated. To define a function, for instance to return the square of a number, type def square(x). Ruby will automatically return the last thing evaluated in the function body, so typing x *x will suffice for the next line. Ruby function definitions end with the end keyword. So the total function definition is:
def square(x)
x*x
end
You can then call this function with square(5) or square 5. The parentheses don't matter, if I'm right. You can also use the return statement, like in other languages.
That's how you define functions and variables in ruby.
No comments:
Post a Comment