3 ms·
> name = details[:info] && details[:info][:name] If you have ActiveSupport, then: > name = details[:info].try {|hash| hash[:name]}
by jrochkind1 14y ago
> name = details[:info] && details[:info][:name]
If you have ActiveSupport, then:
> name = details[:info].try {|hash| hash[:name]}
- caiusdurling 14y agoObject#try should work in plain 1.9 too, although I'm not sure I'd have reached for it in this case. This was more about showing the DRYing up a (visual) pattern across two lines into a different construct though, so perhaps I would've used try if it was just one line somewhere in my code. That said, I didn't know try could take a block instead of a symbol, so thanks for sharing :-)
- nthj 14y agoI like the fetch method too: > name = details[:info].try(:fetch, :name) > => 'Bob'