Data Types

Numbers, Strings, Arrays, Ranges & Hashes.

Numbers

Keep in mind that every value in Ruby is an object, including the operators +, -, /, used in operations are happening between objects.

>> 2**5
=> 32
>> 10/2
=> 5
>> 4.odd?
=> false
>> 10.next
=> 11
>> 10.pred
=> 9
>> 25.to_s
=> "25"
>> 65.chr
=> "A"
>> -5.abs
=> 5

Strings

Another built-in Ruby class. Create strings with single and double quotes.

# Single quotes only support two escape sequences:
>> 'It\'s funny'
=> "It's funny"
>> '\\backslash!'
=> \backslash!

Array

An Array is an Object containing other Objects (including other Arrays) accessible through an Index.

=> arr = Array.new(2)
=> arr = [] 
=> arr = ['uno', 'dos']
=> arr << 'tres'         # ['uno', 'dos', 'tres']

Ranges and Hash

Ranges: allows data to be represented in the form of a range, consisting in a start value and and end value.

>> ('a'..'f').to_a
=> ["a", "b", "c", "d", "e", "f"]

# 3 dots notation excludes last element
>> ('a'...'f').to_a
=> ["a", "b", "c", "d", "e"]

>> ("hi 1".."hi 4").to_a
=> ["hi 1", "hi 2", "hi 3", "hi 4"]

>> (1.1..4.4).step.to_a
=> [1.1, 2.1, 3.1, 4.1]

Hashes: similar to Arrays but acting as dictionaries. This is, they can use an index to reference an object.

This index can be also an object instead of an integer. Arrays use integers as index.

>> hash = { "a" => "Hi", "b" => "There"}
>> hash             # => {"a"=>"Hi", "b"=>"There"}
>> hash['a']        # => "Hi"

Last updated