Back to Home

Array [ ] and Hash { }

Date: Jan 11, 2015

Array [ ]

Definition: Arrays are ordered, integer-indexed collections of any object

Consider Array as a house. House of full of stuff(object). What can go into an array?

How to create an Array?

Array can be made by using iteral constructor

myarray = Array.new: This will return myarray = [] Array.new(3): This will return [nil, nil, nil] Array.new(3, true): This will return [true,true,true]

Why 'array' [ ] is useful and important?

There are several reasons. First, because array is indexed collection of object, an element can be easily retrive. Here is an examples

#Using index to select the smallest integer in the array def smallest_integer(list_of_nums) list_of_nums.sort! return list_of_nums[0] end #Using 'last' key word to select the lasrgest integer in the array def largest_integer(list_of_nums) list_of_nums.sort! return list_of_nums.last end

It is also possible to use cool tricks in array. This is an example of using 'concat' to add two arrays

#array_concat will return array_1 + array_2 def array_concat(array_1, array_2) if array_1.empty? and array_2.empty? return [] end if array_1 == array_2 return array_1.concat(array_2) else return array_1.concat(array_2).uniq end end

The keyword 'uniq' is used to get rid of duplicated element. Pretty neat, huh?


Hash { }

Definition: Hash is the set of 'key' and 'value' pair

As same as array, hash is also easy to retrive their element. The difference is array uses integer index, hash is using any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

How to create a hash

Similar to array, hash can be created by using iteral constructor

myhash = Hash.new: This will return myhash = {} myhash["telephone"] = 650-331-2222: This is same as myhash{"telephone" => 650-331-2222 } myhash[:banana] = 3

Why 'hash' { } is useful and important?

Because hash does have key and value pair, it is useful to store more dynamic data than array. For instance, if you are developing a 'contact list' the contact list can be consist of:

  • 1. Name
  • 2. Telephone number
  • 3. Address
  • By using key and value pair, this can be easily achieved and stored nicely in the hash

    contact_list{"Name" => "Sarah Kwak"} contact_list{"Telephone_number" => 650-332-2222} contact_list{"Address" => "144 Belvedere Ave. San Carlos, CA 94070"}
    #Other way to create hash my_info = { :first_name=> "Sarah", :last_name=> "Kwak", :hometown=> "Seoul, Korea", :age=> 35 }

    The stored information can be easily retrived by using key or value. Here are some cool examples using hash

    # shortest_string is a method that takes an array of strings as its input and returns the shortest string def shortest_string(list_of_words) if list_of_words.length !=0 hash = {} list_of_words.each do |word| hash[word] = word.length end hash.sort_by { |key, value| value }[0][0] else return nil end end