Data Constructors

What Are They?

Constructors are a quick way to create an instance of a class. Today we will check out constructors for Ruby's composite data structures(Hash and Array).


Hash constructors are created by calling Hash[] and passing in either:

  1. a set of keys and values in pairs seperated by commas
  2. an array with nested arrays that contain key-value pairs
  3. key-value pairs
Take a look at the example pulled from RubyDocs

Note that the 2nd option required the nested array. We can use the Array methods .transpose or .zip in conjunction with .map to modify our data structure so that we could create a data structure that would fit our Hash constructor. Once you think you've figured that out, then try to imagine what would be created from this! Note the map will create another array. Hint: if I use [0]["name"] on the new hash, I should return "Joe Schmo". If I use [1]["name], then I get "Ms. Buckets"


Array Constructors are much more simpler than their hash counterparts. You can create Arrays by:

  1. explicitly create an array with
  2. passing in a number argument to for number of elements in new array
  3. passing in a second argument to for default object in each element of array.

Therefore if we used a constructor,true) we would get