Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a similar solution as Array#wrap for hashes?

I use Array.wrap(x) all the time in order to ensure that Array methods actually exist on an object before calling them.

What is the best way to similarly ensure a Hash?

Example:

def ensure_hash(x)
  # TODO: this is what I'm looking for
end
values = [nil,1,[],{},'',:a,1.0]
values.all?{|x| ensure_hash(x).respond_to?(:keys) } # true
like image 707
Nathan Hanna Avatar asked Sep 06 '25 05:09

Nathan Hanna


1 Answers

The best I've been able to come up with so far is:

Hash::try_convert(x) || {}

However, I would prefer something more elegant.

like image 179
Nathan Hanna Avatar answered Sep 07 '25 19:09

Nathan Hanna