Build a File Type Hash Mapper in Ruby

Whether it’s a complex coding interview question or algorithm implementation, there are many times where you will be asked to combine a large number of processes into a single feature. In this guide we’ll examine how to build a non-trivial program that takes in an array of file names and generates a hash collection where each file type is the key and the value is an array of their respective file names.

Summary

Build a method that takes in an array of file names and filters them into an organized hash.

Exercise File

Code File

Exercise Description

Given an array of file names (with file extensions), build a method that splits the array into a hash where the keys are the file types and the values are arrays that contain the file name.

Example

file_names = %w{file1.rb file2.html file3.rb file4.rb file5.js}

# Result should be:
{
  'rb' => ['file1', 'file3', 'file4'],
  'html' => ['file2'],
  'js' => ['file5']
}

Real World Usage

This is a non-trivial exercise. In order to properly implement this solution you will need to utilize the following valuable skills:

  • Opening up the Array class and adding a custom method
  • Iterating over an array and dynamically building a hash with default empty arrays for each of the values
  • Working with custom File methods
  • Implement string parsing methods to clean up output

Solution

Can be found on the solutions branch on github.

Jordan Hudgens

view all post
Leave a comment

Please be polite. We appreciate that.

By Daniele Zedda • 18 February

← PREV POST

By Daniele Zedda • 18 February

NEXT POST → 34
Share on