Tuesday, May 15, 2012

How do you declare variables and functions in ruby?

As it turns out, declaring variables and functions in ruby is fairly simple. To declare a variable, simply take a name, like string for instance, and assign it to a value with an = sign. For example, string = 'hello' would bind the name string to the string literal hello. Then, for example, puts(string) would print hello.

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