I want to extract a value by using try
in Ruby.
I found there are two ways of doing this and was playing around with it in irb.
>> hash = { a: 1, b: 2 }
=> {:a=>1, :b=>2}
>> hash.try(:a)
=> nil
>> hash.try(:[], :a)
=> 1
I have two questions,
hash.try(:[], :a)
and hash.try(:a)
? I searched around and found people use both ways.hash.try(:[], :a)
# 1
Tries to invoke the public method []
on hash
passing as :a
as argument to []
. As :a
is an existing key in the hash, it returns its value.
hash.try(:a)
# nil
Tries to invoke the public method :a
on hash
. As hash
as the receiver doesn't respond to :a
then it returns nil
.
As a clarification, the arguments for try
are as first the method to be invoked on the receiver, and all the other arguments are the arguments for the method being invoked.
If your hash could respond to the method :a
, hash.try(:a)
would return the value of that method being called on hash
:
# Just for example purposes
class Hash; def a; :a_monkey_patched_value_for_a; end
hash.try(:a)
# :a_monkey_patched_value_for_a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With