Hashes | Ruby for Beginners (2024)

Dictionaries: look up one thing by another

Hashes are another very useful, and widely used kind of thing that can be usedto store other objects.

Unlike arrays which are mere lists, Hashes are like dictionaries:

You can use them to look up one thing by another thing. We say: we look up avalue from a Hash using a key. Or one could say: Please get me the value thatis associated with this key.

Imagine a real dictionary that translates from English to German. When youlook up the English word “hello” then you’ll find the German “Hallo”. Whenyou look up “one” then you’ll find “eins”, and so on. The authors of thisdictionary have assigned a German word (a value) to an English word (the key).

Hashes work pretty much like this.

A Hash assigns values to keys, so that values can be looked up by their key.

We also refer to a value that is assigned to a key as key/value pairs. AHash can have as many key/value pairs as you like.

Creating a Hash

In Ruby you can create a Hash by assigning a key to a value with =>, separatethese key/value pairs with commas, and enclose the whole thing with curlybraces.

This is how it looks:

{ "one" => "eins", "two" => "zwei", "three" => "drei" }

This defines a Hash that contains 3 key/value pairs, meaning that we can lookup three values (the strings "eins", "zwei", and "drei") using threedifferent keys (the strings "one", "two", and "three").

By the way, the Ruby community has come up with the name hash rocket for thebit of syntax => which separates a key from a value, … we think that ispretty cool to know :)

A Hash is created by listing key/value pairs, separated by hash rockets, and enclosed by curly braces.

Looking up a value

Now, how do you actually look up the value that is associated with the key"one"?

Just like with Arrays you use sqare brackets, but instead of passinga number indicating the position you now pass the key. Like so:

dictionary = { "one" => "eins", "two" => "zwei", "three" => "drei" }puts dictionary["one"]

Do you reckognize how we, on the second line, use a variable name torefer to the Hash defined on the first line?

In this example, dictionary is a Hash defined on the first line. ["one"]looks up the value associated to the key "one", which is "eins". This valuewill be passed to puts which outputs it to the screen.

Setting a key to a value

Also, just like with Arrays, there’s a way to set key/value pairs on an existingHash:

dictionary = { "one" => "eins", "two" => "zwei", "three" => "drei" }dictionary["zero"] = "null"puts dictionary["zero"]

This prints out null.

You could also overwrite existing key/values the same way. For example thiswould set the word "uno" to the key "one" (i.e. overwrite the existing pairwith the value "eins"):

dictionary = { "one" => "eins", "two" => "zwei", "three" => "drei" }dictionary["one"] = "uno"puts dictionary["one"]

So, this would now output uno.

Any kind of objects

You can use any kind of object as keys, and you can store any kind of objectas values.

For example, these are all valid Hashes, too:

{ 1 => "eins", 2 => "zwei", 3 => "drei" }{ :one => "eins", :two => "zwei", :three => "drei" }{ "weights" => ["pound", "kilogram"], "lengths" => ["meter", "mile"] }{ :de => { :one => "eins", :two => "zwei", :three => "drei" } }

The first example uses numbers as keys, while the second one uses Symbols,which is quite a common thing to do in Ruby.

In the third example you can see that one can use Arrays as values in Hashes.So if you’d look up the key "weights" you’d now get an Array back.

Not quite sure where you’d use a Hash like the third line in real code, but thelast line is actually pretty darn close to what Rails uses for translatingstrings to different languages:

It is also an example of a nested Hash. There’s another Hash associated(stored) as a value for the key :de (representing the language German). Andthis other Hash now has three key/value pairs. So a Rails programmer could lookup how to translate “one” to German, and get “eins” back.

Hashes can use any kind of objects as keys and values.

On formatting: Note that there’s one space inside the curly braces on bothsides, around the => Hash rocket, and after each comma. But thereare, again, no spaces inside that square brackets [] that definethe Arrays on the third line.

Missing values

What happens if we try to look up a key that does not exist?

Again, just as with Arrays, we’ll get back nil, meaning “nothing”:

$ irb> dictionary = { "one" => "eins", "two" => "zwei", "three" => "drei" }> dictionary["four"]=> nil

Does this make sense?

Things you can do with Hashes

The main purpose of a Hash is being able to lookup a value by a key.

However, here are a few other things you can do with Hashes, too.

Again, look at them, and play with them in irb. Don’t necessarily put toomuch effort into memorizing all of them …

You can merge two Hashes:

$ irb> { "one" => "eins" }.merge({ "two" => "zwei" })=> { "one" => "eins", "two" => "zwei" }

fetch does just the same as the square bracket lookup [] discussed before,but it will raise an error if the key is not defined:

$ irb> dictionary = { "one" => "eins" }> dictionary.fetch("one")=> "eins"> dictionary.fetch("two")KeyError: key not found: "two"

keys returns an Array with all the keys that a Hash knows:

$ irb> dictionary = { "one" => "eins", "two" => "zwei" }> dictionary.keys=> ["one", "two"]

length and size both tell how many key/value pairs the Hash has:

$ irb> dictionary = { "one" => "eins", "two" => "zwei" }> dictionary.length=> 2> dictionary.size=> 2

Exercises: Now would be a good time to do some of the exercises onHashes.

Hash syntax confusion

You can skip the following and jump right to the chapter Variables,or you can keep reading if you’re curious.

We’ve found it’s important for us to explain the following somewhere in ourbook, because many online resources use another, alternative syntax fordefining Hashes.

The term syntax, in programming, refers to ways to use punctuation in orderto (amongst other things) create objects.

E.g. the fact that we can use square brackets [] and commas , in order todefine Arrays, and curly braces {} and hash rockets => in order to defineHashes, is part of Ruby’s syntax.

Today, there are two different syntaxes for defining Hashes with curly braces,and they have the potential to confuse newcomers a lot.

There’s an old-style one, and a new, modern one.

We use the old syntax, and ignore the new one, for now.

Here’s why:

Up to a certain version of Ruby the syntax that uses hash rockets was the onlysyntax to create Hashes, and it works the same for all Hashes no matter whatkinds of objects you use as keys.

Then, a few years back, a new syntax was introduced. Many Ruby programmers loveto use it, because it takes a little less space, and it also looks a lot likeJSON, which is a data format that is widely used in web applications.

The new Hash syntax looks like this:

{ one: "eins", two: "zwei", three: "drei" }

Using this syntax we tell Ruby that we want the keys to be symbols.

Hmmmm? We just learned that Symbols are defined by prepending a word with acolon like :one, right?

Well, yes, correct, but that’s just how it works: If you define a Hash usingthis syntax, then you’ll get a Hash that has Symbols as keys.

We found the new syntax pretty confusing for beginners: It is slightly lessexplicit and obvious, and you have to learn another piece of information.That’s why we simply ignore it in our study groups while we learn what Hashesare and how you can use them.

Once you feel comfortable using Hashes, you can make your own decision, andstart using the modern syntax if you like it better.

In the meanwhile, whenever you see a Hash using the new syntax somewhere else,you now know what it means, and where to look it up. Simply remember that thesetwo Hashes are exactly the same:

{ :one => "eins", :two => "zwei", :three => "drei" }{ one: "eins", two: "zwei", three: "drei" }
Hashes | Ruby for Beginners (2024)
Top Articles
Ecommerce Conversion Rate: Benchmarks & Insights for 2024
Top 15 Tips for Customer Service in Real Estate to Thrive Your Career
Jack Doherty Lpsg
Express Pay Cspire
My E Chart Elliot
Guardians Of The Galaxy Showtimes Near Athol Cinemas 8
Sam's Club Gas Price Hilliard
Palace Pizza Joplin
Costco in Hawthorne (14501 Hindry Ave)
Graveguard Set Bloodborne
83600 Block Of 11Th Street East Palmdale Ca
Hillside Funeral Home Washington Nc Obituaries
Nonuclub
Sports Clips Plant City
Scholarships | New Mexico State University
Hartland Liquidation Oconomowoc
Rainfall Map Oklahoma
Craigslist Free Stuff Santa Cruz
Sport-News heute – Schweiz & International | aktuell im Ticker
Urban Dictionary: hungolomghononoloughongous
Whitefish Bay Calendar
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Dover Nh Power Outage
Epguides Strange New Worlds
Shopmonsterus Reviews
Timeforce Choctaw
Dcf Training Number
Company History - Horizon NJ Health
Craigslistodessa
Synergy Grand Rapids Public Schools
Inter Miami Vs Fc Dallas Total Sportek
Giantbodybuilder.com
Best Town Hall 11
Florence Y'alls Standings
Bi State Schedule
UPC Code Lookup: Free UPC Code Lookup With Major Retailers
Emily Katherine Correro
Pnc Bank Routing Number Cincinnati
About | Swan Medical Group
Amici Pizza Los Alamitos
Linabelfiore Of
Flashscore.com Live Football Scores Livescore
Jefferson Parish Dump Wall Blvd
Sams La Habra Gas Price
Craigslist Pets Huntsville Alabama
Has any non-Muslim here who read the Quran and unironically ENJOYED it?
Kent And Pelczar Obituaries
Craigslist Mendocino
Syrie Funeral Home Obituary
Laura Houston Wbap
Basic requirements | UC Admissions
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 5494

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.