2.6. Variables

You already know that everything in Ruby is an object. So a variable must also be an object.

Naming Conventions

Normal variables are written in lower case. Constants start with an upper case letter.

Important

A constant can also be overwritten with a new value in Ruby (but you will get a warning message). So please do not rely on the constancy of a constant.
You are on the safe side if you are using only ASCII symbols. But with Ruby 1.9 and the right encoding, you could also use special characters (for example German umlauts) more or less without any problems in a variable name. But if you want to be polite towards other programmers who probably do not have those characters directly available on their keyboards, it is better to use only pure ASCII.

Strings

Let's experiment a little bit in the irb. The method .class tells us which class we are dealing with.
$ irb --simple-prompt
>> a = 'First test'
=> "First test"
>> a.class
=> String
That was easy. As you can see, Ruby automagically creates an object of the class String. We could also do this by explicitly calling the method new:
>> b = String.new('Second test')
=> "Second test"
>> b.class
=> String
If we call String.new without a parameter, this also creates an object of the class String. But it is an empty String:
>> c = String.new
=> ""
>> c.class
=> String
>> exit
$ 

Single and Double Quotations Marks

Note

Please note: if we mention single or double quotation marks in the context of strings, we do not mean typographically correct curly quotation marks (see http://en.wikipedia.org/wiki/Quotation_mark), but the ASCII symbols referred to as apostrophe (') or quotation mark (").
Strings can be defined either in single quotes or double quotes. There is a special feature for the double quotes: you can integrate expressions with the construct #{}. The result is then automatically inserted in the corresponding place in the string.
Example:
$ irb --simple-prompt
>> a = 'blue'
=> "blue"
>> b = "Color: #{a}"
=> "Color: blue"
>> b.class
=> String
>> exit
$
If the result of the expression is not a string, Ruby tries to apply the method to_s in order to convert the value of the object into a string.

Integers

Fixnum and Bignum

Fixnum and Bignum are Integer classes. A Fixnum is an Integer that can be saved in a Word.[14]If a Fixnum gets bigger, it automatically becomes a Bignum. Here is an example where a becomes larger and by that becomes a Bignum.
$ irb --simple-prompt
>> 20.class
=> Fixnum
>> a = 20
=> 20
>> a.class
=> Fixnum
>> a = a * 5555555555
=> 111111111100
>> a.class
=> Fixnum
>> a = a * 5555555555
=> 617283950493827160500
>> a.class
=> Bignum
>> exit
$ 

Floats

Float is a class for real numbers (floating point numbers). The decimal separator is a point (not a comma, as in some European countries).
$ irb --simple-prompt
>> a = 20.424
=> 20.424
>> a.class
=> Float
>> 42.2.class
=> Float
>> exit
$

Simple Calculations

Calculating with integers and floats is so easy that you can describe everything with just a few lines of code in the irb:
$ irb --simple-prompt
>> a = 10
=> 10
>> b = 23
=> 23
>> a + b
=> 33
>> (a + b).class
=> Fixnum
>> c = a + b
=> 33
>> c.class
=> Fixnum
>> d = 3.14
=> 3.14
>> e = a + d
=> 13.14
>> e.class
=> Float
>> a * b
=> 230
>> (a * b).class
=> Fixnum
>> (a * b * d).class
=> Float
>> exit
$

Boolean Values and nil

For boolean values (true and false) and for nil (no value) there are separate classes:
$ irb --simple-prompt
>> true.class
=> TrueClass
>> false.class
=> FalseClass
>> nil.class
=> NilClass
>> exit
$
nil (no value [15]) is, by the way, the contraction of the Latin word nihil (nothing [16]) or, if you look at it in terms of programming history, the term derives from not in list from the legacy of the programming language Lisp (the name is an acronym of List Processing).

Scope of Variables

Variables have a different scope (or reach) within the Ruby application and therefore also within a Ruby on Rails application. You need to keep this scope in mind while programming. otherwise you can end up with odd effects.

Local Variables (aaa or _aaa)

Local variables either start with a lower case letter or an underscore (_). Their scope is limited to the current environment (for example the current method). The follwing example defines two methods which use the same local variable radius. Because they are local they don't interact with each other:
$ irb --simple-prompt
>> def area(radius)
>>   3.14 * radius * radius
>> end
=> nil
>> def circumference(radius)
>>   2 * 3.14 * radius
>> end
=> nil
>> area(10)
=> 314.0
>> circumference(1)
=> 6.28
>> exit
$

Global Variables ($aaa)

A global variable starts with a $-sign and is accessible in the entire programm. Example:
$ irb --simple-prompt
>> $value = 10
=> 10
>> puts $value
10
=> nil
>> def example
>>   $value = 20
>> end
=> nil
>> puts $value
10
=> nil
>> example
=> 20
>> puts $value
20
=> nil
>> exit
$
Global variables are used very rarely.

Instance Variables (@aaa)

Instance variables (Attributes, hence the @) only apply within a class, but everywhere in it – a mini version of global variables, so to speak. Unlike global variables, you will find instance variables all over the place in a Rails application. Let's tackle them in form of an example program with the name color.rb:
class Wall
  def initialize
    @color = 'white'
  end
  
  def color
    @color
  end

  def paint_it(value)
    @color = value
  end
end

my_wall = Wall.new
puts my_wall.color

my_wall.paint_it('red')
puts my_wall.color
If you start this program, the following output will appear:
$ ruby color.rb 
white
red
$
In the method initialize we set the instance variable @color to the value white. The method paint_it(value) changes this instance variable.
With the method color we can access the value of @color outside of the instance. This kind of method is called a setter method.


[14] If you do not know what a Word is: never mind.

Updates about this book will be published on my Twitter feed.