<

Majd's Blog

Ruby: Arrays and Hashes

Fri 3/13/15

>

This entry will be about Arrays and Hashes in Ruby. I'll cover what these are, how to create new arrays and hashes, and some basic methods for each.

First off, what is are these things? Well, sometimes, you have to store some things in lists. In this case, an Array will store the list in an order, with a built-in numbered index (more on this in a second) which looks like this: [0,1,2,"three",4]. A Hash will store things in a key: value pair. Like this: {"k1"=>"v1","k2"=>"v2"} where k means key and v means value.

Arrays are basically like Hashes in that the value is the element you see, and the key is actually its index (position in the array). For example,

array = ["one", "two", "three"]
array[0] = "one"

Here, the index 0 is actually the first position. Important to note that the numbering indexes always starts with 0. Anyway, in this way, the "key" in an array is the index, and the "value" is the element at that index. A hash with the keys all numbered starting from 0 would return the same value if called. The point is, though, that hashes can be used to use a different key than just a numbered index.

Arrays

Creating Arrays

  1. Literal Constructor
    • array_name = []
    • Can add any number of elements separated by commas.
  2. array_name = Array.new
    • Creates empty array.
    • array_name = Array.new(3) creates an array with 3 "nil" elements.
    • array_name = Array.new(3, "abc") creates an array with three "abc" elements: ["abc", "abc", "abc"]
    • array_name = Array.new(3){"abc"} does the same thing.
  3. Array Method
    • Converts what you've got into an array
    • To check if these work, try string.respond_to?(:to_ary) or string.respond_to?(:to_a)
    • .to_ary (No strings!)
    • .to_a (No strings!)
    • Array(string) yields [string]

Calling elements in an Array

Add and remove elements

Combining Arrays

Transform Array

Array Query

Hashes

Creating Hashes

  1. Literal Constructor
    • h = {"k1"=>"v1", "k2"=>"v2", etc.}
    • Can add any number of paired key/value pairs separated by commas.
  2. h = Hash.new
    • Creates empty hash.
    • h = Hash.new(3) Sets default value at 3 for non-existant keys
    • h.default(value) Sets default value.
    • h = Hash.new {|hash, key| hash[key]=0} Makes it so if a nonexistant key is called, it will add that key to the hash with the default value of 0.
  3. Hash.[] Where [] includes an EVEN number elements, will order the pairs as key/value pairs, so 0=>1, 2=>3 and so on. Can also work with nested arrays.
  4. something.to_hash Will turn that something, usually an array, into a hash. If the argument doesn't have to_hash as a method, fatal error occurs.

Adding to Hash

Calling in Hash

Combining Hashes

Select/Reject in Hashes

Transforming Hashes

Query in Hashes

Well, that's a lot! But hopefully will be helpful as a guide for myself and others in the future.