Hashes  And Its Methods in Ruby

Hashes And Its Methods in Ruby

Ruby is a dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

What is a Ruby hash?

A hash is an efficient data structure that lets you store data in UNIQUE key-value pairs. It’s like a kind of dictionary that you can build & use to quickly search for something.

The “word” in this dictionary is the key, and the “definitions” are the values stored under each key.

Why hashes in ruby?

In Ruby, hashes are extensively used due to several key advantages they offer:

  1. Efficient Data Handling: Hashes offer fast data retrieval, ensuring quick access to values based on their associated keys, which is crucial for managing large datasets and frequent data access.
  2. Flexible Key Types and Values: Ruby hashes accommodate various key types and values, allowing developers to use meaningful identifiers and diverse data representations, which enhances code readability and versatility.
  3. Predictable Insertion Order (Ruby 1.9+): Hashes in Ruby maintain the order of insertion, promoting code predictability during iteration and ensuring consistent behavior, particularly useful for maintaining ordered collections and reliable code execution.

How is this different from arrays?

Well, arrays store data in a sequential, numerical index, so the only way to retrieve a specific item is to know this index number, which by itself doesn’t have much meaning.

But hash keys can be normal words like “stock_available”, which have meaning & therefore are easier to work with.

So you’ll use arrays for LISTS of things (like a list of fruits) & hashes for a DICTIONARY of values.


1- How to Create a Hash

I think you got a general idea of what is a hash, but how do you create one?

There is a variety of ways to create hashes.

1- The first way:

1.   my_hash = { }          

A hash with three key/value pairs looks like this:

1.  my_hash ={  a: 1 , b: 2 ,  c: 3  }        

2- The second way:

Create an empty hash with the new class method

1. months = Hash.new        

You can also use new to create a hash with a default value, which is otherwise just nil

1.   months = Hash.new( "month" )

or

2.   months = Hash.new "month"        

3- The thrid way:

1.    another_hash  =  Hash["a" => 100, "b" => 200]

2.    puts     "#{another_hash['a']}"
3.    puts    "#{another_hash['b']}"        

This will produce the following result

1.    100
2.    200        

2- Storing Hash Values

You can create a hash with a set of initial values, as we have already seen.

1.    fruits  = { coconut: 1, apple: 2, banana: 3 }        

Another option is to add new values to an existing hash.

1.    fruits[:orange] = 4        

3- How to Access Values From a Hash

You access a hash by key.

If you need to access the values directly, then a hash may not be the right structure for your data.

Example:

1.    fruits[:orange]
2.    # 4        

If a key doesn’t exist, you’ll get nil.

1.    fruits[:peach]
2.    # nil        

As an alternative, you can use the fetch method, which allows you to provide a default value.:

Example:

1.    fruits.fetch(:peach, 0)        

If you use fetch without a default value (the 2nd argument), Ruby will raise a KeyError exception.

4- How to Merge Two Ruby Hashes

You can take two hashes & merge them into a new hash.

Well, it’s not hard to guess this one. The method’s name is merge.

Here’s how to use it:

1.    defaults    = { a: 1, b: 2, c: 3 }
2.    preferences = { c: 4 }

3.    defaults.merge!(preferences)
4.    # {:a=>1, :b=>2, :c=>4}        

Notice that because keys are unique, newer values overwrite older values

You could use this fact for interesting solutions, like creating a “defaults” hash that users can override by passing their own hash.

If you need more control over how keys are merged you can pass a block.

Like this:

1.    defaults.merge!(preferences) { |key, old, new| [old, new].max }        

Where old are the values coming from defaults, and new are the values coming from preferences.

5-How to Sort a Hash

You can sort arrays. But did you know that you can also sort hashes?

When you sort a hash, it’s sorted by key.

Example:

1.    # Sorting by key
2.    hash1 = { b: 1, a: 2 }
3.    sorted_by_key = hash1.sort.to_h
4.    puts sorted_by_key.inspect

5.    # Sorting by key
6.    {:a=>2, :b=>1}        

But you can also sort them by value:

1.    # Sorting by value
2.    hash2 = { c: 3, b: 1, a: 2 }
3.    sorted_by_value = hash2.sort_by(&:last).to_h   # the result without to_h is array
4.    puts sorted_by_value.inspect

5.    # Sorting by value
6.    [[:b, 1], [:a, 2], [:c, 3]]        

Notice that I use the to_h method to convert arrays that result from methods sort_by and sort back into hashes.

6- How to all key-value pairs from hash.

hash.clear: Removes all key-value pairs from hash.

1.    # Create a hash
2.    hash = { "a" => 100, "b" => 200 }

3.    # Display the original hash
4.    puts "Original hash: #{hash}"

5.    # Clear the hash
6.    hash.clear

7.    # Display the cleared hash
8.    puts "Cleared hash: #{hash}"        

7- How to replaces the contents of hash with the contents of other_hash.

hash.replace(other_hash)

1.     # Create the original hash
2.     hash = { "a" => 100, "b" => 200 }

3.     # Display the original hash
4.     puts "Original hash: #{hash}"

5.     # Create another hash
6.     other_hash = { "x" => 300, "y" => 400 }

7.     # Replace the contents of the original hash with the contents of the other hash
8.     hash.replace(other_hash)

9.     # Display the modified hash
10.     puts "Modified hash: #{hash}"        

8- How to Get the size of the hash

hash.size

1.     # Create a hash
2.     hash = { "a" => 100, "b" => 200, "c" => 300 }

3.     # Get the size of the hash
4.     size = hash.size

5.     # Display the size of the hash
6.     puts "Size of the hash: #{size}"        

9- How to returns a new array containing the values of hash.

There is two methods:

1- hash.values: Returns a new array containing all the values of hash.

1.     hash = { "a" => 100, "b" => 200, "c" => 300 }

2.     # Get all values of the hash
3.     values = hash.values

4.     # Display the values of the hash
5.     puts "Values of the hash: #{values}"        

2- hash.values_at(obj, ...): Returns a new array containing the values from hash that are associated with the given key or keys.

1.     hash = { "a" => 100, "b" => 200, "c" => 300 }

2.     # Get values associated with specific keys
3.     selected_values = hash.values_at("a", "c")

4.     # Display the selected values
5.     puts "Selected values: #{selected_values}"        

Conclusion

"In wrapping up our exploration of Ruby's hash structures, we've uncovered a treasure trove of versatility and efficiency. Yet, our journey through the world of hashes is far from over.

These hash structures aren't just tools; they're powerfull, offering an array of functionalities for organizing and managing data. From simple mappings to complex data relationships, hashes in Ruby are indispensable.

What's more, their lightning-fast data access, thanks to clever internal structures and hashing functions, makes them a go-to solution for any developer. And with Ruby's rich set of built-in methods tailored specifically for hashes, the possibilities are endless.

So, as you continue your coding adventures, remember to leverage the power of hashes. They're not just a feature; they're a gateway to cleaner, more expressive, and scalable code. Embrace the elegance of hashes, and watch your Ruby projects soar to new heights."

Thanks for providing insightful and in-depth guide about hashes in ruby, keep it up 👏 👏

Impressive work as usual from you 👏👏👏

To view or add a comment, sign in

Others also viewed

Explore content categories