Arrays and Hashes
Published: 2024-01-24 02:45:34

_Codecademy Cheatsheet_

**Ruby Array**

In Ruby, an array is an ordered collection of Ruby objects separated by commas and enclosed in `[]`. An array can contain the same or different types of Ruby objects, such as Integers, Strings, Floats, etc. An array can also be empty.

```
numbers = [1, 2, 3, 4, 5]
#An array of Integers

words = ["See", "Spot", "run"]
#An array of Strings

mixed = ["hello", 5, true, 3.0]
#An array with a String, Integer, Boolean, and Float

empty = []
#An empty array
```

---
**Ruby Array Index**

In Ruby, each item inside of an array is at a numbered position called an _index_. The first item is at index 0, the second item is at index 1, and so on. We can access the `i`th element of an array by putting the index in square brackets after invoking the array’s name; this is known as access by _index_

```
example = ["Car", "Boar", 45, 9.9, true]

#For an array named `example`, you can retrieve an item of a particular index by referencing its index.

puts example[2] # => 45
puts example[0] # => Car
```
---

**Arrays of Arrays**

```
multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

multi_d_array.each { |x| puts "#{x}\n" }

#[0, 0, 0, 0]

#[0, 0, 0, 0]

#[0, 0, 0, 0]

#[0, 0, 0, 0]

```

---
  
**Ruby Hash**

In Ruby, a _hash_ is a collection of key-value pairs.

A _hash_ is denoted by a set of curly braces (`{}`) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket (`=>`). Calling the `hash` followed by a key name within brackets grabs the value associated with that key.
 

```
profile = {
  "name" => "Magnus",
  "profession" => "chess player",
  "ranking" => 1,
  "grandmaster?" => true
}

# "name", "profession", "ranking", and "grandmaster?" are the keys. "Magnus", "chess player", 1 and true are the values.

puts profile["name"] # => Magnus

```
P.S Hashes are like JS objects. 

---

**Ruby Hash New**

In Ruby, a _hash_ can be created through literal notation (because we are literally assigning what `key=>value` pairs we want in the hash) or by assigning a variable equal to `Hash.new` which generates a new, empty hash.

```
#Creating a hash through literal notation:
lunch = {
  "protein" => "chicken",
  "greens" => "lettuce",
  "organic?" => true
}

#Creating a hash through Hash.new
lunch = Hash.new
puts lunch # => {}
```

---
**Adding to a Hash**
We can add to a hash two ways: if we created it using literal notation, we can simply add a new key-value pair directly between the curly braces. If we used `Hash.new`, we can add to the hash using bracket notation:

```
pets = Hash.new
pets["Stevie"] = "cat"
# Adds the key "Stevie" with the
# value "cat" to the hash

```
---
**Ruby Method .Each**

In Ruby, the `.each` method is used to iterate over arrays and hashes. This allows each element in an array and each key-value pair in a hash to be iterated.

```
#In this example, the each method iterates over every color in the colors array and prints it to the console.

colors = ["red", "blue", "green", "yellow"]

colors.each { |color| puts color }
#Output
#red
#blue
#green
#yellow

#When iterating over hashes, two placeholder variables are needed to represent each key/value pair.

polygons = {
  "pentagon" => 5,
  "hexagon" => 6,
  "nonagon" => 9
}

polygons.each do |shape, sides|
  puts "A #{shape} has #{sides} sides."
end
#Output
#A pentagon has 5 sides.
#A hexagon has 6 sides.
#A nonagon has 9 sides.
```

---
**Iterating Over Multidimensional Arrays**

```
s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

s.each { | sub_array | sub_array.each { | item | puts item} }
  
#or 

s.each do | sub_array |
  sub_array.each do | y |
    puts y
  end
end
```

---
**Iterating Over Hashes**

When iterating over hashes, we need two placeholder variables to represent each key/value pair.

```
restaurant_menu = {
  "noodles" => 4,
  "soup" => 3,
  "salad" => 2
}

restaurant_menu.each do |item, price|
  puts "#{item}: #{price}"
end
```

---
**Sorting the Hash**

```
colors = { 
  "blue" => 3,
  "green" => 1,
  "red" => 2
}
colors = colors.sort_by do |color, count|
  count
end
colors.reverse!

```
1. In the example above, we first create a hash called `colors` that maps color strings to numbers.
2. Then, we sort `colors` into green, red, and blue, from smallest to largest by count. Just so you know, the `.sort_by` function returns an array of arrays, but that’s fine for our purposes.
3. Finally, we reverse the array order so that the colors with the largest counts are first.

---
**CREATE A HISTOGRAM**

```
puts "Enter a phrase you'd like to analyze: "
text = gets.chomp

words = text.split

frequencies = Hash.new(0)

words.each { |word| frequencies[word] += 1 }

frequencies = frequencies.sort_by { |word, count|
  count }


frequencies.reverse!

frequencies.each { |word, count|
  puts word + " " + count.to_s }

```