Collections: Working with Hashes in Ruby

Hashes are data structures that contain key => value pairs and are denoted by curly braces {}

hash = {:key => value}  # old syntax
hash = {key: value} #new syntax

They can have multiple key value pairs.

hash = {:key1 => value1, :key2 => value2, :key3 => value3}

To add onto a hash:

hash[:key4] = value4
hash[:key5] = value5
# => {:key1 => value1, :key2 => value2, 
      :key3 => value3, :key4 => value4, :key5 => value5}

To delete a key and its value:

hash = {:key2 => value2, :key3 => value3, :key4 => value4, :key5 => value5}

To retrieve a value of a specific key:

# => value5

hash.merge(other_hash) merges hash with other_hash and creates another hash.

hash.merge!(other_hash) is a mutating version that modifies the calling hash object.

Iterate with .each method

hash.each { |key, value| puts #{key} #{value} }



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s