Datatypes

in Ruby: booleans, symbols, numbers, strings, arrays, and hashes

"hello" # is a string!

Booleans
There are only two values of the Boolean data type: true and false. In Ruby, however, there is no such thing as a Boolean class. Instead, every appearance, or instance, of true and false in your program are instances of TrueClass and FalseClass respectively.

Numbers
You probably already know from the real world (as opposed to the Ruby world) that integers are numbers. In Ruby, there are two types of numbers: Fixnums and Floats.
Fixnums are whole numbers, like 7.
Floats are decimal numbers, like 7.3.

There are a number of methods available to you for operating on or manipulating integers.For now, we'll just check out a few examples:

7.5.floor          
// => this method will round the float down to the nearest fixnum. Here it will return 7        
7.5.ceil          
// => 8          
10.next          
// => 11

Symbols
A symbol is a representation of a piece of data. Symbols look like this :my_symbol. If I make a symbol, :my_symbol, and then use that symbol later on in my code, my program will refer to the same area of memory in both cases. This is different from, for example, strings, which take up new areas of memory every time they are used.

Creating Symbols
You write symbols by placing a : in front of the symbol name. :this_is_a_symbol

Arrays are collections of Ruby objects. You can store any type of data in an array.

There are a number of ways to create an array. Just like with creating strings, you can use the literal constructor or the class constructor.
The Literal Constructor:[1, 3, 400, 7] is an array of integers. Any set of comma separated data enclosed in brackets is an array. So, by simply writing something like the above, you can create an array. The Class Constructor: You can also create an array with the Array.new syntax. Just typing Array.new will create an empty array (=> []).

There are many ways to operate on arrays and on each individual item, or element, within an array

[5, 100, 234, 7, 2].sort
// => [2, 5, 7, 100, 234]

[1, 2, 3].reverse
// => [3, 2, 1]

Hashes

Hashes also store objects in Ruby. However, they differ from arrays in that they function like dictionaries. Instead of a simple comma separated list, hashes are composed of key/value pairs. Each key points to a specific value––just like a word and a definition in a regular dictionary.

Hashes look like this:

{"i'm a key" => "i'm a value!", "key2" => "value2"}

The curly brackets denote the hash and this particular hash has two key/value pairs.

Creating Hashes

Hashes can be created with literal constructors and class constructors.

The Literal Constructor:You can create a hash by simply writing key/value pairs enclosed in curly braces.

The Class Constructor:Or, you can use the Hash.newsyntax, which would create an empty hash, {}.

results matching ""

    No results matching ""