Ruby advance hash learning
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 advance ruby's hash concept and I am sure you will get excited to make your hands dirty with those code, so why to wait let's get started...
If you already read my previous post on Ruby hash and its methods then you can easily find out the key difference between this post and that post after completing the reading of this one. But if you didn't read or if you are not sure how ruby's hash works, then you can go to read the basics and then can easily understand this complex hash post.
Till the time we may have seen the hash as in key, value pair and mostly key is in String or Symbol type. But it's not limited to this only, In ruby the key of the Hash can be a Data type, Array, A complex (nested) array or even the ruby's Kernel. Yes, you read correctly, But before this let us see one more power of ruby's hash for providing the default values whenever there are key not found occurs. Well most of the time it happens that we might access some key which is not present in the hash so at that time rather than returning nil we may return something valuable, how?, let's see....
As you can see, on line #3, if will access a key which is not present in the hash then will get nil, whereas, if will initialise the default in the time of initialising the hash as on the line #8, then it would be great to receive something useful and user friendly rather than just the nil value.
But what it so good in it if it will always return me a boring static value, why not to config it to return some value based on the key passed. So as you can see line #14 for hash3 in the code, we may handle the default value to return some dynamic content based on the key value. But the complexity is not only limited to this, As you can see on the line #23 for hash4 , we can even check the class of the key and put some conditions and get the desire outcome.
Well, this all we learned is to handle default value of the ruby's hash. Now we will also see some of the key's property of ruby's hash. For that you can go through the code below,
🤪 What?, What is line #9 in the code, Amazed!!!, Well it shows one thing "Any object can be a key in Ruby's Hash", As you can see the classes such as String, Fixnum and Boolean values that are true and false all can be used as the key.
At line #12, we have the expression, which first get the class of a text, which comes as String and then the key will be passed as String, to get the hash value which comes as, 'This is string class'.
Now I think enough reading, I would suggest you to open your rails terminal and play with the code! 💻
Comments
Post a Comment