Phase 0 - Week 3 Arrays vs Hases
Friday, May 15, 2015
This week we learned about Arrays and Hashes and while they are very similar, they both have different strengths and weaknesses. Some people feel that Hashes are better because they are more efficient while others feel that the looping ability of Arrays is beneficial. From everything that I have read so far, /I feel that they are both beneficial when used properly. To start out, I would like to talk a little about how to use each.
Arrays are ordered, integer indexed collections that can be used to store any object. Indices start at 0 and reference positions in the array and negative indices are relative to the end of the array. Arrays can be created by using the Literal Constructor [] or explicitly by using Array.new.
Literal Notation
New Constructor
Because Arrays are integer indexed, it is easy to refer to a specific index to assign and/or change the value. In addition, it is easy to loop through arrays to work with the objects stored in it. In addition, there are plenty of built-in methods that can be called upon any Array Object. Below is a list of built-in Array Methods:
Hashes are a collection of key & value pairs like this: “First Name” => “David”. Hashes are similar to Arrays, except that they are indexed with user defined unique keys. Since Hashes are not integer indexed, the order in which you iterate through a hash may seem arbitrary and it may not be in the order items were added. Just like Arrays, Hashes can be created by using the Literal Notation as well as the New Constructor.
Literal Notation
New Constructor
One of the main benefits of using Hashes is speed, they are considered to be much more efficient than other data structures despite the fact they can be difficult to implement. Similar to Arrays, Hashes have built-in functions that can be called upon to work with both the keys and values stored within them. Below is a list of the Hash Methods:
So the Big Question still remains, which is better Arrays or Hashes??? I don't we have enough experience yet to really make that call.There are definite advantages and disadvantages to both; however, I would love to hear from you. Do you have a preference? Let me know and I will write a follow-up to this posting summarizing the responses I receive.