Ruby Hashes - A Detailed Guide (2023)

What is a Hash?

A hash is a data structure that stores items by associated keys. This is contrasted against arrays, which store items by an ordered index. Entries in a hash are often referred to as key-value pairs. This creates an associative representation of data.

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated.

Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.

irb :001 > old_syntax_hash = {:name => 'bob'}=> {:name=>'bob'}

The newer syntax is introduced in Ruby version 1.9 and is much simpler. As you can see, the result is the same.

irb :002 > new_hash = {name: 'bob'}=> {:name=>'bob'}

You can also have hashes with many key-value pairs.

irb :003 > person = { height: '6 ft', weight: '160 lbs' }=> {:height=>'6 ft', :weight=>'160 lbs'}

Let's say you wanted to add on to an existing hash.

irb :004 > person[:hair] = 'brown'=> "brown"irb :005 > person=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown'}irb :006> person[:age] = 62=> 62irb :007> person=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown', :age=>62}

And what if you want to remove something from an existing hash?

(Video) Ruby Tutorial - Hashes

irb :008 > person.delete(:age)=> 62irb :009 > person=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown'}

Now how do you retrieve a piece of information from a hash?

irb :010 > person[:weight]=> "160 lbs"

What if you want to merge two hashes together?

irb :011 > person.merge!(new_hash)=> {:height=>'6 ft', :weight=>'160 lbs', :hair=>'brown', :name=>'bob'}

Notice that we used the bang suffix (!) to make this change destructive. We could have chosen to use the merge method instead, which would have returned a new merged hash, but left the original person hash unmodified.

Iterating Over Hashes

Because hashes can have multiple elements in them, there will be times when you'll want to iterate over a hash to do something with each element. Iterating over hashes is similar to iterating over arrays with some small differences. We'll use the each method again and this time we'll create a new file to test this out.

# iterating_over_hashes.rbperson = {name: 'bob', height: '6 ft', weight: '160 lbs', hair: 'brown'}person.each do |key, value| puts "Bob's #{key} is #{value}"end

We use the each method like before, but this time we assign a variable to both the key and the value. In this example we are setting the key to the key variable and the value to the value variable. Run this program at the command line with ruby iterating_over_hashes.rb to see the results. The output is:

Bob's name is bobBob's height is 6 ftBob's weight is 160 lbsBob's hair is brown

Hashes as Optional Parameters

You may recall in chapter three on methods, we talked about the ability to assign default parameters to your methods so that the output is always consistent. You can use a hash to accept optional parameters when you are creating methods as well. This can be helpful when you want to give your methods some more flexibility and expressivity. More options, if you will! Let's create a method that does just that.

# optional_parameters.rbdef greeting(name, options = {}) if options.empty? puts "Hi, my name is #{name}" else puts "Hi, my name is #{name} and I'm #{options[:age]}" + " years old and I live in #{options[:city]}." endendgreeting("Bob")greeting("Bob", {age: 62, city: "New York City"})

We used Ruby hash's empty? method to detect whether the options parameter, which is a hash, had anything passed into it. You haven't seen this method yet but you can infer what it does. You could also check out the Ruby Docs to look up the method as well. At the end we called the method twice. Once using no optional parameters, and a second time using a hash to send the optional parameters. You can see how using this feature could make your methods much more expressive and dynamic.

(Video) Ruby Hashes Explained

And finally, to add a small twist, you can also pass in arguments to the greeting method like this:

greeting("Bob", age: 62, city: "New York City")

Notice the curly braces, { }, are not required when a hash is the last argument, and the effect is identical to the previous example. This convention is commonly used by Rails developers. Understanding this concept alone should help you decipher some previously cryptic Rails code!

Hashes vs. Arrays

This chapter and the last covered two very important and widely used data structures: hashes and arrays. It can be a bit overwhelming when you look at all of the different ways there are to represent data with code. Don't feel too daunted. Pick these things up in small parts and apply them. Then add more little parts as you move along. It's impossible to know everything in the beginning so put some effort into learning a few things well and then build from there.

When deciding whether to use a hash or an array, ask yourself a few questions:

  • Does this data need to be associated with a specific label? If yes, use a hash. If the data doesn't have a natural label, then typically an array will work fine.

  • Does order matter? If yes, then use an array. As of Ruby 1.9, hashes also maintain order, but usually ordered items are stored in an array.

  • Do I need a "stack" or a "queue" structure? Arrays are good at mimicking simple "first-in-first-out" queues, or "last-in-first-out" stacks.

    (Video) 3 Ways of Creating Hashes in Ruby

As you grow as a developer, your familiarity with these two data structures will naturally affect which one you reach for when looking to solve specific problems. The key is to practice and experiment with each to find out which data structure works best in certain situations.

A Note on Hash Keys

Thus far, we have been using symbols as our keys in all of the hashes we've been creating. We have done this because it is the most common use case in the wild. However, it is possible to use a different data type for a key. Let's take a look.

irb :001 > {"height" => "6 ft"} # string as key=> {"height"=>"6 ft"}irb :002 > {["height"] => "6 ft"} # array as key=> {["height"]=>"6 ft"}irb :003 > {1 => "one"} # integer as key=> {1=>"one"}irb :004 > {45.324 => "forty-five point something"} # float as key=> {45.324=>"forty-five point something"}irb :005 > {{key: "key"} => "hash as a key"} # hash as key=> {{:key=>"key"}=>"hash as a key"}

Pretty bizarre. So you can see that hashes can be very diverse and you can pretty much store whatever you want to in them. Also notice that we are forced to use the old style (i.e., using =>) when we deviate from using symbols as keys.

Common Hash Methods

Let's look at some common methods that come with Ruby's Hash class.

key?

The key? method allows you to check if a hash contains a specific key. It returns a boolean value.

irb :001 > name_and_age = { "Bob" => 42, "Steve" => 31, "Joe" => 19}=> {"Bob"=>42, "Steve"=>31, "Joe"=>19}irb :002 > name_and_age.key?("Steve")=> trueirb :003 > name_and_age.key?("Larry")=> false

select

The select method allows you to pass a block and will return any key-value pairs that evaluate to true when passed to the block.

irb :004 > name_and_age.select { |k,v| k == "Bob" }=> {"Bob"=>42}irb :005 > name_and_age.select { |k,v| (k == "Bob") || (v == 19) }=> {"Bob"=>42, "Joe"=>19}

fetch

The fetch method allows you to pass a given key and it will return the value for that key if it exists. You can also specify an option for return if that key is not present. Take a look at the Ruby docs here to see what else is possible.

(Video) Ruby Data Structures : Hashes - A closer look at Ruby’s Built in Hash Methods

irb :006 > name_and_age.fetch("Steve")=> 31irb :007 > name_and_age.fetch("Larry")=> KeyError: key not found: "Larry" from (irb):32:in `fetch' from (irb):32 from /usr/local/rvm/rubies/ruby-2.5.3/bin/irb:16:in `<main>'irb :008 > name_and_age.fetch("Larry", "Larry isn't in this hash")=> "Larry isn't in this hash"

to_a

The to_a method returns an array version of your hash when called. Let's see it in action. It doesn't modify the hash permanently though.

irb :009 > name_and_age.to_a=> [["Bob", 42], ["Steve", 31], ["Joe", 19]]irb :010 > name_and_age=> {"Bob"=>42, "Steve"=>31, "Joe"=>19}

keys and values

Finally, if you want to just retrieve all the keys or all the values out of a hash, you can do so very easily:

irb :0011 > name_and_age.keys=> ["Bob", "Steve", "Joe"]irb :0012 > name_and_age.values=> [42, 31, 19]

Notice that the returned values are in array format. Because it's returning an array, you can do interesting things like printing out all the keys in a hash: name_and_age.keys.each { |k| puts k }.

A Note on Hash Order

In the oldest versions of Ruby, you could not rely on hashes maintaining order; that is, the order in which keys/value pairs are stored was not well-defined. On one call to name_and_age.keys, we might see ["Bob", "Steve", "Joe"]; in a subsequent run of the program, we might get ["Joe", "Bob", "Steve"].

In all modern Ruby versions (1.9 and higher), hashes maintain the order in which they're stored. Thus, the following code will always output the same results: ["Steve", "Joe", "Bob"]:

irb :013 > name_and_age = { "Steve" => 31, "Joe" => 19, "Bob" => 42 }=> { "Steve" => 31, "Joe" => 19, "Bob" => 42 }irb :014 > name_and_age.keys=> ["Steve", "Joe", "Bob"]

Summary

Now you have a good start at knowing all of the wonderful things that hashes can do. The concept of key-value pairs will come up quite often in other technologies as well, so it's good to have a tight grasp on it. I think you know what's coming next...more exercises!

FAQs

How to use hashes in Ruby? ›

In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.

What do you understand by hashes in Ruby? ›

A Ruby hash is a collection of unique keys and their values. They are similar to arrays but array use integer as an index and hash use any object type. They are also called associative arrays, dictionaries or maps. If a hash is accessed with a key that does not exist, the method will return nil.

How to list all keys of hash in Ruby? ›

Code
  1. h1 = {one: 1, two: 2, three: 3}
  2. h2 = {name: "okwudili", stack: "ruby"}
  3. h3 = {"foo": 0, "bar": 1}
  4. h4 = {M:"Mango", A: "Apple", B: "Banana"}
  5. puts "#{h1. keys}"
  6. puts "#{h2. keys}"
  7. puts "#{h3. keys}"
  8. puts "#{h4. keys}"

Why do we use hashes in Ruby? ›

Using a hash in your Ruby programs can speed up your code when used in the right situation. In other words: You have data that is (or can be transformed into) a dictionary-like format, where data can be grouped by keys & associated values.

What is the best way to create a hash in Ruby? ›

Creating a Hash

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

What is the difference between array and hash in Ruby? ›

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.

What is the difference between hash and dictionary in Ruby? ›

Dictionary. The Ruby Hash is an implementation of the dictionary concept, where the keys (in the key, value pair) are unique numbers. A dictionary is a general concept that maps unique keys to non-unique values.

What are the two types of hashes? ›

There are multiple types of hashing algorithms, but the most common are Message Digest 5 (MD5) and Secure Hashing Algorithm (SHA) 1 and 2.

How to check key-value of a hash in Ruby? ›

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

Can a ruby hash have duplicate keys? ›

The hash contains duplicate keys. While this is allowed by Ruby, this usually happens due to typos, and is, in most cases, unintended.

How do you select an item from a hash in Ruby? ›

In Ruby, we make use of the select() method when we want to find the array from the hash based on the condition and we make use of the select!() method when we want to check whether the array from the hash is present or not.

How to convert hash keys to string in Ruby? ›

simply call stringify_keys (or stringify_keys! ) Save this answer.

When should we not use hashes? ›

There are some operations which are not efficiently supported by hash tables, such as iterating over all the elements whose keys are within a certain range, finding the element with the largest key or smallest key, and so on. The O(n) complexity is on average.

What are hashes good for? ›

So, here, hashing is used to index and retrieve information from a database because it helps accelerate the process; it is much easier to find an item using its shorter hashed key than its original value.

Why do people use hashes? ›

Hashing helps to both encrypt and decrypt digital signatures, which are mathematical algorithms used to routinely validate the authenticity and integrity of a digital document or message. Hash functions transform the digital signature before the hash value, and the signature gets sent to the receiver.

Can you map a hash Ruby? ›

Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.

How to sort hash by keys in Ruby? ›

The sort_by function

It contains numerical and alphabetical values. Using the sort_by function, we first sort the hash according to its values using last as a condition. It is clear as the puts method prints 1 , 2 , and 3 in order. After this, we use first to sort the hash by its keys.

How to check if hash is empty in Ruby? ›

When we say a Hash is empty, what we mean is that the Hash has no entries. We can use the empty? method to check if a Hash has no entries. This method returns a Boolean, which indicates whether the Hash is empty or not.

Is HashMap better than array? ›

Arrays can have duplicate values, while HashMap cannot have duplicated keys (but they can have identical values.) The Array has a key (index) that is always a number from 0 to max value, while in a HashMap, you have control of the key, and it can be whatever you want: number, string, or symbol.

Why use hash tables instead of arrays? ›

With arrays: if you know the value, you have to search on average half the values (unless sorted) to find its location. With hashes: the location is generated based on the value. So, given that value again, you can calculate the same hash you calculated when inserting.

Why is hash faster than array? ›

Searching over a data structure such as an array presents a linear time complexity of O(n). In other words, as the data structure increases in size, the search time increases in a linear fashion. Simply put, using a hash table is faster than searching through an array.

What is the difference between store and merge in Ruby hash? ›

store is an assignment method. merge on the other hand manipulates your existing hash by merging with a different hash. However unless you use merge! a 's value will not get changed i.e. merge will occur only for return.

What is the difference between colon and arrow in hash Ruby? ›

A hash — similar to an array — is a Data Structure.

To build hashes there are two unique syntaxes. There is the fat-arrow “=>”, used to assign a key to the value, but there's also the newer ruby syntax which introduces a colon on the end of the key to separate the key and value.

Should I use Hashtable or dictionary? ›

A Dictionary<TKey,TValue> of a specific type (other than Object) provides better performance than a Hashtable for value types. This is because the elements of Hashtable are of type Object; therefore, boxing and unboxing typically occur when you store or retrieve a value type.

What are the 3 commonly used hash functions? ›

Types of Hash functions
  • Division Method.
  • Mid Square Method.
  • Folding Method.
  • Multiplication Method.
Mar 10, 2023

What is the best hash type? ›

To protect passwords, experts suggest using a strong and slow hashing algorithm like Argon2 or Bcrypt, combined with salt (or even better, with salt and pepper). (Basically, avoid faster algorithms for this usage.) To verify file signatures and certificates, SHA-256 is among your best hashing algorithm choices.

Do hashes have keys? ›

The basic operation of hash functions does not need any key and operate in a one-way manner. The one-way operation means that it is impossible to compute the input from a particular output. The basic uses of hash functions are: Generation and verification of digital signatures.

How to remove key values from hash in Ruby? ›

There are many ways to remove a key from a hash and get the remaining hash in Ruby.
  1. slice => It will return selected keys and not delete them from the original hash. ...
  2. delete => It will delete the selected keys from the original hash(it can accept only one key and not more than one).

What is the default value for a key in Ruby hash? ›

Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil .

What is the symbol for hash keys in Ruby? ›

In Ruby hashes, key symbols and their values can be defined in either of two ways, using a => or : to separate symbol keys from values. #Key symbols and their values can be defined with a =>, also known as a hash rocket.

What is the difference between symbol and string hash key in Ruby? ›

While symbols and strings give you the same results when used as keys in hashes, they are not the same thing. A symbol is immutable while a string is mutable. You can't change a symbol once it's created. :locked on different lines in your code is the same object.

How to merge hash in Ruby? ›

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

What is the difference between hash clone and dup in Ruby? ›

In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance. When using dup, any modules that the object has been extended with will not be copied.

How to change the value of a hash in Ruby? ›

The contents of a certain hash can be replaced in Ruby by using the replace() method.

How to use hash in class in Ruby? ›

Public Class Methods
  1. Hash[ key, value, ... ] → new_hash. Hash[ [ [key, value], ... ] ] ...
  2. new → new_hash. new(obj) → new_hash. new {|hash, key| block } → new_hash. ...
  3. try_convert(obj) → hash or nil. Try to convert obj into a hash, using #to_hash method. Returns converted hash or nil if obj cannot be converted for any reason.

How to join hash in Ruby? ›

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

How to insert a key in an hash in Ruby? ›

How to add elements to a Hash in Ruby?
  1. Method 1: Use Hash.store() method. ...
  2. Syntax: Hash_object.store(key,value)
  3. Parameter(s) required: ...
  4. Program:
May 7, 2020

How do you check if a key exists in a hash Ruby? ›

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How to map a hash in Ruby? ›

Let's make a Ruby hash map method that returns a hash instead of...
  1. > [1,2,3]. map{ |i| i+1 } => [2, 3, 4] ...
  2. > { "x" => 1, "y" => 2, "z" => 3 }. map{ |k,v| { k. ...
  3. x = {} (1.. 10000). ...
  4. Hash[x. map {|k, v| [k. ...
  5. class Hash def hmap(&block) Hash[self. map {|k, v| block. ...
  6. x = {} (1.. 10000).

How to check hash value in Ruby? ›

Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .

What is the default hash method in Ruby? ›

Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil .

Videos

1. A Better Way to Query Hash Values in Ruby
(edutechional)
2. Hash Methods in Ruby
(APPSIMPACT Academy)
3. How to Sort the Keys of a Hash in Ruby
(edutechional)
4. Ruby Programming Tutorial - 32 - Methods for Hashes
(thenewboston)
5. How To Use Ruby Hashes In the Most Effective Way
(Jesus Castello)
6. BDO - Ultimate Hashashin Guide for 2023 Awakening & Succession
(ShakyBay)

References

Top Articles
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated: 09/07/2023

Views: 6028

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.