Hash in Ruby
Explore how to create and manipulate hashes in Ruby by defining key-value pairs using symbols and strings. Understand different hash syntaxes, how to access values by keys, and the significance of symbols versus strings as keys in hashes.
We'll cover the following...
Defining hash in Ruby
To define a hash in a Ruby program, we need to use curly brackets. Remember that we use square brackets for arrays:
$ pry
> obj = {}
...
> obj.class
Hash < Object
We should not name the variable hash because it is a reserved language keyword, but we can enter it into the REPL and see what happens. That’s why the authors usually use obj (object) orhh(double “h” indicates it’s more than just a variable).
Programmers say that the hash is key-value storage, where each key is assigned a value. For example, the key is ball, a string, and the value is the physical object ball itself. The hash is often called a ...