Understanding Ruby Variables

Revision as of 16:48, 14 November 2007 by Neil (Talk | contribs) (Declaring a Variable)

Revision as of 16:48, 14 November 2007 by Neil (Talk | contribs) (Declaring a Variable)

Variables are essentially a way to store a value and assigning a name to that value. Variables take various forms ranging from integers to strings of characters.

Ruby and Variable Dynamic Typing

Many languages such as Java and C use what is known as strong or static variable typing. This means that when you declare a variable in your application code you must define the variable type. For example if the variable is required to store an integer value, you must declare the variable as an integer type. With such languages, when a varaible has been declared as a particular type, the type cannot be changed.

Ruby, on the other hand, is a dynamically typed language. This has a couple of key advantages. Firstly it means that you do not need to declare a type when creating a variable. Instead, the Ruby interpreter looks at the type of value you are assigning to the variable and dynamically works out the variable type. Another advantage of this is that once a variable has bene declared, you dynamically change the variable type later in your script.

Declaring a Variable

Variables are declined and assigned values by placing the variable name and the value either side of the assignment operator (=). For example, to assign a value of 10 to a variable we will designate as y we would write the following:

y = 10

We have now created a variable called y and assigned it the value of 10.

In common with some other scripting languages, Ruby supports something called parallel assignment. This is useful if you need to assign values to a number of variables. One way to do this would be as follows:

a = 10
b = 20
c = 30
d = 40

The same result can be achieved more quickly, however, using parallel assignment:

a, b, c, d = 10, 20, 30, 40

Identifying a Ruby Variable Type

Once a Ruby variable has been declared it can often be helpful to find out what type the variable has been assigned. This can be achieved using the kind_of? method of the Object class). For example, to find out if our variable is an Integer we can use the kind_of? method:

y.kind_of? Integer
=> true

We can also ask the variable exactly what class of variable it is:

y.class
=> Fixnum

This tells us that the variable is a fixed number class.

Similarly, we could perform the same task on a string variable we will call s:

s = "hello"
s.class
=> String

Here we see that the variable is of type String.

Changing Variable Type