3.4. Ruby's Essential Data Types

Ruby offers a wide range of data types that you can use in your programs and Rails applications. Being a dynamic language, when it comes to types, Ruby is slightly different from what you may have seen in compiled languages such as C, C++, C#, Visual Basic, or Java. Fortunately, working with Ruby data types tends to be much easier.

3.4.1. Everything Is an Object

.NET developers are familiar with the Common Type System (CTS), in which there are two broad categories of types: Value types and Reference types. Among the Value types there are the built-in value types such as System.Int32, System.Double, or System.Boolean.

Other languages like C, C++ (outside of the .NET Framework), and Java may use different names and a different terminology, but they all essentially distinguish between "primitive" types and actual full-fledged classes. In these languages, there are objects, like instances of the class Array, and then there are primitive types that you can't inherit from, call a method on, retrieve or set a property for, and so on.

Forget all that. In Ruby that distinction doesn't exist. Here are a few examples of perfectly valid Ruby code:

3.zero?     # Equivalent to 3 == 0
-5.abs      # 5
12.to_f     # 12.0
15.div(3)   # 5
9.9.round   # 10
true.to_s   # "true"
nil.nil?    # true

This example just called methods on simple numbers, true, and even nil (Ruby's version of null). How is that possible? In Ruby every value is an object!

Ruby methods can end with a question mark, ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.