Introduction

In this write-up, we will continue with my previous article and will explore more collections in Ruby on Rails. I hope it will help you to dive deep into Ruby. Here is the link to my previous article.

What we will learn here?

  • Hashes and Symbols.
    • Hashes.
    • Symbols.
    • Methods of Hashes.
    • Nested Arrays.
    • Nested Hashes.
  • Iterators.
  • Letter Frequency Counter.

Hashes & Symbols

Hashes

Example

Collections Of Ruby On Rails
Symbols

Syntax

a = id

Example

Collections Of Ruby On Rails
In the code above, symbols are used as keys for our hash.
Methods of Hashes

Example

Collections Of Ruby On Rails
Nested Arrays
Arrays can contain other arrays. These are called nested arrays.

Example

Collections Of Ruby On Rails

Note
The arr array contains two arrays. So, arr[1][2] accesses the second array’s third element, which is 6.

Example

Collections Of Ruby On Rails
Hashes and arrays can have any level of nesting, but keep in mind that hashes and arrays with more than three dimensions are harder to manage.

Iterators

Example

Collections Of Ruby On Rails

Note
Here, x denotes the elements of arrays.

Example

Collections Of Ruby On Rails
The Each iterator can also be used with hashes.

Example

Collections Of Ruby On Rails

Example

Collections Of Ruby On Rails

Example

Collections Of Ruby On Rails

Letter Frequency Counter

Letter Frequency
Let’s create a program that will count the frequency of letters (numbers of occurrences) in a given string. First, we need a string.

Example

  1. Text = “I am learning Ruby and it is fun!”
  2. Text.downcase!

Example

  1. Freqs = {}
  2. Freqs.default = 0

Example

  1. Text.each_char{|char| freqs[char] + = 1}

Example

  1. (“a”..”z”).each{|x| puts “#{x}:#{freqs[x]}”}
We do this because not all letters of the alphabet are contained in our text.

Example

Collections Of Ruby On Rails
Collections Of Ruby On Rails

Summary

Today, we learned some interesting concepts. In the future, we will see some more on this. If you have any queries, please ask me.