Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 279
catlovespurple Avatar asked Oct 16 '25 04:10

catlovespurple


1 Answers

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
like image 177
Sebastian Palma Avatar answered Oct 17 '25 17:10

Sebastian Palma