Changes

Jump to: navigation, search

Understanding Ruby Variables

1,122 bytes added, 20:51, 14 November 2007
Changing Variable Type
== Changing Variable Type ==
 
One of simplest ways to change the type of a variable is to simply assign a new value to it. Ruby is dynamically change the type for that variable to match the type of the value assigned. For example, we can create a variable containing an integer and verify the type:
 
<pre>
x = 10
=> 10
x.class
=> Fixnum
</pre>
 
Suppose, we now want to store a string in a variable named 'x'. All we need to do is make the assignment, and Ruby will change the variable type for us:
 
<pre>
x = "hello"
=> "hello"
x.class
=> String
</pre>
 
As we can see, the x variable is now a string. It is important to note that this is a somewhat destructive way to change a variable type. Often. somehting more subtle is needed. For example, we might want to read the value form a variable but convert the extracted value to a different type. Some variable classes have a collection of methods that can be called to convert their value to a different type. For example, the ''Fixnum'' class has method named ''to_f'' that can be used to retrieve the integer stored in a variable as a floating point value:
 
<pre>
y = 20
=> 20
y.to_f
=> 20.0
</pre>

Navigation menu