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:
- a set of keys and values in pairs seperated by commas
- an array with nested arrays that contain key-value pairs
- key-value pairs
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 ["name"] on the new hash, I should return "Joe Schmo". If I use ["name], then I get "Ms. Buckets"
Array Constructors are much more simpler than their hash counterparts. You can create Arrays by:
- explicitly create an array with Array.new
- passing in a number argument to Array.new() for number of elements in new array
- passing in a second argument to Array.new() for default object in each element of array.
Therefore if we used a constructor Array.new(3,true) we would get