Data Collections in Ruby

Array

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 …


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Abraão Carvalho

Array

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
   Orange
   Mango

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

arr = Array.new    => []
Array.new(3)       => [nil, nil, nil]
Array.new(3, true) => [true, true, true]

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:

Array.new(4) {Hash.new}    => [{}, {}, {}, {}]
Array.new(4) {|i| i.to_s } => ["0", "1", "2", "3"]

Hash

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"}

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"}

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"

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]
end

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
  end

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

  alias eql? ==

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

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

reviews = {}

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

reviews.length #=> 1


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Abraão Carvalho


Print Share Comment Cite Upload Translate Updates
APA

Abraão Carvalho | Sciencx (2023-01-09T14:02:17+00:00) Data Collections in Ruby. Retrieved from https://www.scien.cx/2023/01/09/data-collections-in-ruby/

MLA
" » Data Collections in Ruby." Abraão Carvalho | Sciencx - Monday January 9, 2023, https://www.scien.cx/2023/01/09/data-collections-in-ruby/
HARVARD
Abraão Carvalho | Sciencx Monday January 9, 2023 » Data Collections in Ruby., viewed ,<https://www.scien.cx/2023/01/09/data-collections-in-ruby/>
VANCOUVER
Abraão Carvalho | Sciencx - » Data Collections in Ruby. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/01/09/data-collections-in-ruby/
CHICAGO
" » Data Collections in Ruby." Abraão Carvalho | Sciencx - Accessed . https://www.scien.cx/2023/01/09/data-collections-in-ruby/
IEEE
" » Data Collections in Ruby." Abraão Carvalho | Sciencx [Online]. Available: https://www.scien.cx/2023/01/09/data-collections-in-ruby/. [Accessed: ]
rf:citation
» Data Collections in Ruby | Abraão Carvalho | Sciencx | https://www.scien.cx/2023/01/09/data-collections-in-ruby/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.