Let’s assume we have to parse this hash. There can be the case we are not getting the keys as a response. So this post is about handling those cases.
Let’s assume we have to parse this hash. There can be the case we are not getting the keys as a response. So this post is about handling those cases.
General Scenario
So in the best case scenario, we will be having all the keys. So the code like this will work.
Exceptional Scenario
Now think about this case when we don’t have location key in the response. So we got a hash like this:
Now in this case
As we all know there is no surety of the hash from the provider so we cant trust it and this ‘nil’ value can, later on, create issues as we start using it assuming everything is coming perfectly fine from the provider.
So if you want to generate an error in this case when key is not found a simple way can be using statement modifiers ie
but there is a better way ie using ‘fetch’
If you are not sure even for info part (which actually you can’t be) then you can chain ie like this:
Use case 1 - Providing a default value
Now if you want to pass a block for a default value which will be executed if and only if that key is not valuated.
Use case 2 - Passing a block
Another use case of fetch is it yields the missing key which can be used as
Caution
Another thing to note with fetch is, there is another way to pass the second parameter is method ie:
But the problem with the second one is default method. This method will be computed every time whether your key exists or not, which can be a problem in case you are doing some heavy computation. Using block will execute if and only if the key doesn’t exist.
Fetch also works on arrays
Another thing to note down is fetch also works on array as it works on hash