Hash
The Hash, which associates arbitrary indexes to arbitrary values, is the most flexible basic class in Ruby. Although Hash does implement each and Enumerable, hashes behave slightly differently than arrays and sets.
Creating Hashes
Hashes have a literal syntax that uses curly braces to associate keys with values. The original form of separating keys from values uses the => symbol, often called a hash rocket:
| hash = {"a" => 1, "b" => 2, "c" => 3} |
In general, you want the hash keys to be immutable values, and symbols are commonly used. If the key is a symbol, then you can use a colon to separate the key from a value. The colon will also convert strings to symbols. The keys in this literal are :a, :b, and :c, all symbols:
| hash = { ... |
Get Programming Ruby 3.3 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.