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
hash   
# => {:key1 => value1, :key2 => value2, 
      :key3 => value3, :key4 => value4, :key5 => value5}

To delete a key and its value:

hash.delete(:key1)
hash = {:key2 => value2, :key3 => value3, :key4 => value4, :key5 => value5}

To retrieve a value of a specific key:

hash[:key5] 
# => 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} }

 

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s