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.
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.
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.
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.
to be added
to be added'
to be added