Ruby Hash and its methods
Hi, This is Shubham Mishra from India, this is the part of Ruby on Rails exploration journey. In this post we will discuss about the ruby's Hash and its methods available to simplify our development and make the code more smarter 😅
Ok then without wasting a time we start looking into Ruby's Hash. If you are new to the development then you can read below or if you are aware of what is hash then you can skip to next paragraph.
Hash: Similar to array the Hash is a collection of objects but in the diffrent fashion. The hash store the items in the form of a key and its value. In short see below image, how lock can be access by the key assigned to it, similar to this only hash works.
Enough theory let jump into it with some example, One important think to remember is Hash will always take unique key, It means one key cannot be considered again in the hash.
students = { | |
'Shubham': 'Expert in maths', | |
'Ashwin': 'Expert in physics', | |
'Sneha': 'Expert in Dance and Art' | |
} | |
students['Ashwin'] | |
# O/p: | |
'Expert in physics' | |
students.keys | |
# O/p: | |
[:Shubham, :Ashwin, :Sneha] | |
students.values | |
# O/p: | |
["Expert in maths", "Expert in physics", "Expert in Dance and Art"] |
Now i think you understood how hash works, now lets jump into some of the hash methods and how can we use it in diffrent ways. But before going ahead you may have seen some hash with keys without string, that is even possible and that is known as Symbol. Have a look into it, (In most of the time I would suggest to go with symbol since in ruby, symbol are more memory efficient than string but that is a diffrent topic, lets stick to the hash only)
students = { | |
Shubham: 'Expert in maths', | |
Ashwin: 'Expert in physics', | |
Sneha: 'Expert in Dance and Art' | |
} | |
students[:Ashwin] | |
# O/p: | |
'Expert in physics' | |
students.keys | |
# O/p: | |
[:Shubham, :Ashwin, :Sneha] | |
students.values | |
# O/p: | |
["Expert in maths", "Expert in physics", "Expert in Dance and Art"] |
Ok lets move with the code only, I think reading unnecessary things is just waist of time, we can learn a more from the code. The first we will have a look on merge
hash1 = {a: 100, b: 200} | |
hash2 = {x: 'Shreya', y: 'Mohit'} | |
# Merging two hash, In this hash1 and hash2 won't change | |
# only new hash will be generated by merging two hash | |
hash1.merge(hash2) | |
# O/P: | |
{:a=>100, :b=>200, :x=>"Shreya", :y=>"Mohit"} | |
# Merging one hash into another by merge!, | |
# In this hash2 will be merged into hash1 | |
# This happens due to ! (Bang) syntax next to merge | |
hash1.merge!(hash2) | |
# O/P: | |
{:a=>100, :b=>200, :x=>"Shreya", :y=>"Mohit"} | |
# After above if you will print hash1 | |
hash1 | |
# O/P: | |
{:a=>100, :b=>200, :x=>"Shreya", :y=>"Mohit"} | |
# Now lets say you may have two hash with same keys but diffrent values | |
# And you want the new generated hash value to be the sum of both the values | |
hash1= {a: 10, b: 20} | |
hash2= {a: 100, b: 200} | |
hash1.merge(hash2) {|key, value1, value2| value1 + value2} | |
# O/P: | |
{:a=>110, :b=>220} | |
# Similar to above you can do any operations in the block |
Now a day we are developing filter and sorting the list on product or other pages, so its necessary to look how can we sort a hash in ruby
# In ruby we have .sort as the method to sort a hash, | |
# by default it will sort based on the keys | |
{shubham: 10, ashwin: 30, zeeshan: 94}.sort | |
# O/P: | |
[[:ashwin, 30], [:shubham, 10], [:zeeshan, 94]] | |
# Got the sorted one but Wait, What it is giving back an array | |
# No worry's we can convert it back into Hash with .to_h | |
{shubham: 10, ashwin: 30, zeeshan: 94}.sort.to_h | |
# O/P: | |
{:ashwin=>30, :shubham=>10, :zeeshan=>94} | |
# Most of the time it happens that we may want to sort the hash based on value rather keys | |
{math: 59, phy: 20, eng: 89}.sort_by(&:last).to_h | |
# O/P: | |
{:phy=>20, :math=>59, :eng=>89} | |
# Wait, in our real life the hash will not be as simple as above, | |
# Now lets take some tough example, Lets say we have few students with marks in 3 subjects, | |
# and now we want to sort students based on their marks in the Math subject, | |
{ shubham: {math: 50, science: 20, history: 25}, | |
nikhil: {math: 40, science: 40, history: 80}, | |
john: {math: 10, science: 70, history: 90} | |
}.sort_by {|key, value| value[:math]}.to_h | |
# O/P: | |
{ :john=>{:math=>10, :science=>70, :history=>90}, | |
:nikhil=>{:math=>40, :science=>40, :history=>80}, | |
:shubham=>{:math=>50, :science=>20, :history=>25} | |
} |
In above code you may have notice that a hash's value could be a hash also. Ok now we will also look into delete methods,
hash1= {a: 100, b: 200, c: 300} | |
hash1.delete(:a) #Notice it will delete the key-value but will return value | |
# O/P: | |
100 | |
# Now hash1 wii be | |
hash1 | |
# O/P: | |
{:b=>200, :c=>300} | |
# As the delete basics is clear now move on for some complex examples, | |
# In this we will remove students those scored less than 15 in Maths | |
hash1 = { shubham: {maths: 50, science: 20, history: 25}, | |
nikhil: {maths: 40, science: 40, history: 80}, | |
john: {maths: 10, science: 70, history: 90} | |
} | |
hash1.delete_if {|key, value| value[:maths] < 15} | |
# Now check hash1 | |
hash1 | |
# O/P: | |
{ :shubham=>{:math=>50, :science=>20, :history=>25}, | |
:nikhil=>{:math=>40, :science=>40, :history=>80} | |
} |
Now I think enough reading, I would suggest you to open your rails terminal and play with the code! 💻
Comments
Post a Comment