RGSS/Variable
Comments0this wiki
< RGSS
In Ruby, variables are - unlike in other programming languages - not bound to a specific type. Instead, their type is changed automatically, depending on the variable's content.
To demonstrate this, let's compare variables in Java and Ruby.
Java:
int a = 5; //variable "a" contains an Integer, 5. a = "testing.."; //a is set to "testing..", a String. //Since a is an Integer, the line above will produce an error.
Ruby:
a = 5 #variable "a" contains 5, an Integer. a = "testing.." #a is set to "testing..", a String. #a is automatically changed from an Integer to a String. #It now contains "testing.." and no error occurred.
As you can see, this greatly simplifies your work. Also, note that you don't have to declare a type for the variable.
There are several different kinds of variables.
Contents |
Local Variables
Edit
Local variables are, as the name suggests, local. This means that they only exist inside the scope they are declared in.
def world txt = "Hello World" print(txt) #print what is contained in txt #=> "Hello World" end
In this example, we created a method world. Inside this method, a variable, txt, is created and set to a value ("Hello World"). After that, the variable is printed, resulting in "Hello World".
This works because print is used inside the scope txt is declared in.
However, if it is not within that scope, it won't work:
def world txt = "Hello World" end print txt #=> error
In this example, print cannot find txt, resulting in an error. This is because txt only exists within the world method and print is used outside of that method.
Instance Variables
Edit
to be added
Global Variables
Edit
to be added'
Constants
Edit
to be added