lundi 15 avril 2019

Ruby: two ways using try in Hash

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,

  1. What is the difference between hash.try(:[], :a) and hash.try(:a)? I searched around and found people use both ways.
  2. I saw a lot of places using hash.try(:a) to retrieve values, but why my trial returns nil?

Aucun commentaire:

Enregistrer un commentaire