Changes

Jump to: navigation, search

Understanding Ruby Variables

2,162 bytes added, 16:44, 14 November 2007
New page: 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 Dyna...
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:

<pre>
y = 10
</pre>

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

== 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:

<pre>
y.kind_of? Integer
=> true
</pre>

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

<pre>
y.class
=> Fixnum
</pre>

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'':

<pre>
s = "hello"
s.class
=> String
</pre>

Here we see that the variable is of type String.

== Changing Variable Type ==

Navigation menu