Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What are hashes in Ruby?

Mohammad Razi ul Haq

A hash is a collection of unique key-value pairs. Hashes are similar to arrays in the way that they store the values against an index. However, arrays use an integer as an index, whereas hashes use object types as an index. A hash assigns values to keys, thus, enabling values to be looked up by their keys.

Create a hash in Ruby

A hash is created by writing the key-value pairs inside curly braces ({}). Values can be accessed by writing the keys in square brackets.

# Create hash
myhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }

# Output a value against a key
puts myhash["k"]

Renaming a key-value pair

A value can also be reassigned against a key. The syntax to do this is shown below.

# Create hash
myhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }

# Output a value against a key
puts myhash["k"]

# Reassign a value to a key
myhash["k"] = 20

# Output the new value against a key
puts myhash["k"]

Adding a new key-value pair to the hash

We can also add new key value pairs to hashes after the initialization. The code below shows that when we reference a non-existent key the output is nothing.

# Create hash
myhash = { "foo"=> 5, "bar"=>"my value", "k"=> 73 }

# Add a new key value pair
myhash["new value"] = 30

puts myhash

# Referencing a non existent key. Nothing is outputted
puts myhash["Non-existent key"]

RELATED TAGS

ruby
communitycreator

CONTRIBUTOR

Mohammad Razi ul Haq
RELATED COURSES

View all Courses

Keep Exploring