Definition:
A collection of key-value pairs. They are like dictionaries.
Hash syntax looks like this:
hash = {
key1 => value1,
key2 => value2,
key3 => value3
}
Values are assigned to keys using =>. Any ruby object can be a key or value.
- Note: This is the literal notation. This is because you literally describe what you want in the hash: you give it a name and you set it equal to one or more key => value pairs inside curly braces.
Using Hash.new
Another way to create a hash is using Hash.new (Hash must be capitalized) like this:
my_hash = Hash.new
This is the same as my_hash = {}
Setting a variable equal to Hash.new creates a new, empty hash.
Adding to a Hash
Three ways:
Literal notation: simply add a new key-value pair directly between the curly braces
Bracket notation: Hash[key] = value
For example:
pets = Hash.new
pets["Stevie"] = "cat"
pets["Lucky"] = "dog"
pets["Sam"] = "snake"
- Using the .store method
students = Hash.new
students.store(:name, "John Doe")
students.store(:age,22)
students.store(:grade,"A")
Accessing Hash Values
Very similar to accessing values in an array.
To access the value, access the key first using brackets:
pets = {
"Stevie" => "cat",
"Bowser" => "hamster",
"Kevin Sorbo" => "fish"}
puts pets["Stevie"]
Top comments (0)