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,
- What is the difference between
hash.try(:[], :a)
andhash.try(:a)
? I searched around and found people use both ways. - I saw a lot of places using hash.try(:a) to retrieve values, but why my trial returns nil?
Aucun commentaire:
Enregistrer un commentaire