Hashes in Ruby

The Hash class is a built-in Ruby object instances of which (hashes) are dedicated to storing and retrieving values under specific keys.

Commonly hashes in Ruby are created using literal constructors.

student_grades = {
  michael: 'A',
  amy: 'A+',
  anthony: 'B'

In the above example symbols are used as keys and the notation michael: A is tantamount to :michael => 'A' where the symbol :michael is a key and the string 'A' is a value. In addition to symbols strings are commonly used as Ruby hashes' keys.

:[] method is used to retrieve a value stored under a specific key. Remember that the symbol :michael is not the same key as the string 'michael'.

student_grades[:michael] # => "A"
student_grades['michael'] # => nil

:[]= method is used to store a new key-value pair in an existing hash.

student_grades[:jenny] = 'C' # => C

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.