Chapter 3.6 Hash

Hash or an associative array/dictionary is a collection of values of any type indexed by other values of any type.

A hash can be called as thathash and maybe called out its keys by name.

gossip = I heard a funny gossip.

manners = Dee is ill-mannered.

crazy = Paranoia drives me crazy.

stop = Stop right now.

thathash['manners'] --> Dee is ill-mannered.

thathash['crazy'] --> Paranoia drives me crazy.

Hashes can be keyed by almost any type because indexes have two requirements:

  • they must implement the .eql? method
  • they must have a constant hash code

To create a new hash, bracket nothing or put a set of key value pairs (indicated by the ”=>” combination) between a set of braces.

the_club = { 'Pril' => 'The Slacker', 'Jores' => 
'The Evil Child', 'Marie' => 'The Master',
'May' => 'The Silent Water', 'Mary' => 'The Lion' }

The new method can also be used for creating hashes.

new_Hash = Hash.new("Not here!")
new_hash ['non-existent key']
--> Not here!

Define keys to add them to a hash. For example, we assume to add a birthplace to a name:

my_club['Mary'] = 'Philippines'

Use the fetch method to reference a hash value.

puts my_club['Pril']
--> The Slacker

The values_at method permits you to provide numerous keys and receive their values in an array.

The shift method returns the first element as an array which contains the key in one element and the value in another.

To test elements in a hash, perform these methods:

The empty? method checks whether or not any elements exist in the hash.

my_club.empty?

--> false

The has_key? method checks the hash to see if the key passed as a parameter exists.

my_club.has_key? ('Jores')

--> true

The has_value? method checks the values of the hash to see if it exists in one of the elements.

my_club.has_value? ('pink and purple')

--> false

To delete an element, call the delete method and provide the key you wish to delete as a parameter.

my_club.delete[ ' Marie' ]

--> The Master

The newly emptied hash is returned if you call the clear method.

my_club.clear --> {}

my_club.empty? --> true

  • Currently 2.96/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 1 comments