Rails ActiveSupport provides
method on an object.
Try is used to call a method on an object if it is not
otherwise return nil.
Try method also be used on a hash key
access the value
nil if the value is not available.
We will also see how we can use fetch to access hash keys.
Let’s take a hash for an example.
Try Hash Key
We can use try to fetch value of a hash key as given below.
As, we can see it returns proper value.
Now, if we use
try to access non-existent key in the hash,
it will return
nil as given in the example below.
Object#send, but it returns
nilif calling object is
- The first argument
:, it’s a method call on object with argument as the hash key.
try is more helpful,
if we want to call method on objects
we are not sure if the calling object is
nil or a valid object.
Using fetch on hash
We can directly access value of hash key in ruby as given below.
It will return value of the key. If the key is not found, it will return
As we can see, the above line using hash access
gives us the same behavior that we had
nil if value for the key
:author is not found.
Otherwise, it returns the value found.
fetch is particularly useful
- Raise an exception if value is not found
- Specify a default value returned if value is not found for the key.
As given in the example above,
it returns value
Admin as specified in
Why don’t we just use hash access or fetch method available on Hash from Ruby?
Well, it depends on the use case. Consider the same example given above.
- If we are sure about the variable
hashis actually a hash, then we can confidently use fetch instead of try
tryreturns nil even if caller is
As you can see, this raises
We can still use plain ruby and guard against raising this exception using safe navigation operator in ruby
To conclude, we should know the minor caveats of each method to decide which should be used. Hope, you found this article helpful in some way.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox