Ruby Programming Exercise: Mapping Array Data in Ruby Using Zip and Splat

In this coding exercise, we walk through how to map array data in Ruby, and specifically how we can build a method that takes in an unlimited number of arrays by leveraging the splat operator.

Summary

Build a method that takes in a set of headers as an array and maps the data from an unlimited number of other arrays to those headers.

Exercise File

Code File

Exercise Description

Given the following arrays:

headers = [
  '1B',
  '2B',
  '3B',
  'SS',
  'C',
  'P',
  'LF',
  'CF',
  'RF'
]

astros = [
  'Gurriel',
  'Altuve',
  'Bregman',
  'Correa',
  'Gattis',
  'Keuchel',
  'Beltran',
  'Springer',
  'Reddick'
]

rangers = [
  'Fielder',
  'Andrus',
  'Odor',
  'Beltre',
  'Lucroy',
  'Darvish',
  'Gomez',
  'Choo',
  'Mazara'
]

Write a program that maps the headers to the associated data elements in the other arrays.

Output Based on Sample Data as Inputs

[["1B", "Gurriel", "Fielder"], ["2B", "Altuve", "Andrus"], ["3B", "Bregman", "Odor"], ["SS", "Correa", "Beltre"], ["C",      "Gattis", "Lucroy"], ["P", "Keuchel", "Darvish"], ["LF", "Beltran", "Gomez"], ["CF", "Springer", "Choo"], ["RF", "Reddick", "Mazara"]]

Real World Usage

This is common anytime you have a situation where you have multiple arrays that need to be combined and mapped together. This practice is common in custom algorithm development as well as data science.

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