DEV Community

Abraão Carvalho
Abraão Carvalho

Posted on


Data Collections in Ruby


Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Creating Arrays

A new array can be created by using the literal constructor []. Arrays can contain different types of objects. For example, the array below contains an Integer, a String and a Float:

fruits = ['Apple', 'Orange', 'Mango']
puts fruits

=> Apple
Enter fullscreen mode Exit fullscreen mode

An array can also be created by explicitly calling with zero, one (the initial size of the Array) or two arguments (the initial size and a default object).

arr =    => []       => [nil, nil, nil], true) => [true, true, true]
Enter fullscreen mode Exit fullscreen mode

Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.

To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays: {}    => [{}, {}, {}, {}] {|i| i.to_s } => ["0", "1", "2", "3"]
Enter fullscreen mode Exit fullscreen mode


A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

A Hash can be easily created by using its implicit form:

band = {"Abraão" => "Guitar", "Pedro" => "Bass", "Juliana" => "Vocal", "Guto" => 'Drums'}

puts band

=> {"Abraão"=>"Guitar", "Pedro"=>"Bass", "Juliana"=>"Vocal", "Guto"=>"Drums"}
Enter fullscreen mode Exit fullscreen mode

Hashes allow an alternate syntax for keys that are symbols. Instead of:

options = { :font_size => 10, :font_family => "Arial" }

puts options

=> {:font_size=>10, :font_family=>"Arial"}

Enter fullscreen mode Exit fullscreen mode

Common Uses

Hashes are an easy way to represent data structures, such as

books           = {}
books[:Tolkien] = "The Lord of the Rings."
books[:golden]  = "The Lord of the Rings is an epic high-fantasy"
Enter fullscreen mode Exit fullscreen mode

Hashes are also commonly used as a way to have named parameters in functions. Note that no brackets are used below. If a hash is the last argument on a method call, no braces are needed, thus creating a really clean interface:

Person.create(name: "Abraão Carvalho", age: 28)

def self.create(params)
  @name = params[:name]
  @age  = params[:age]
Enter fullscreen mode Exit fullscreen mode

Hash Keys

Two objects refer to the same hash key when their hash value is identical and the two objects are eql? to each other. A user-defined class may be used as a hash key if the hash and eql? methods are overridden to provide meaningful behavior. By default, separate instances refer to separate hash keys.

A typical implementation of hash is based on the object's data while eql? is usually aliased to the overridden == method:

class Book
  attr_reader :author, :title

  def initialize(author, title)
    @author = author
    @title = title

  def == (other)
    self.class === other and == @author and
      other.title == @title

  alias eql? ==

  def hash
    @author.hash ^ @title.hash # XOR

book1 = 'tolkien', 'The Lord of the Rings is an epic high-fantasy'
book2 = 'tolkien', 'The Lord of the Rings is an epic high-fantasy'

reviews = {}

reviews[book1] = 'Great reference!'
reviews[book2] = 'Nice and compact!'

reviews.length #=> 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git