Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 9, 2023 02:02 pm GMT

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 arraythat 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 = {"Abrao" => "Guitar", "Pedro" => "Bass", "Juliana" => "Vocal", "Guto" => 'Drums'}puts band=> {"Abrao"=>"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: "Abrao 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  endendbook1 = 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

Original Link: https://dev.to/abraaocrvlh42/data-collections-in-ruby-10h4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To