Avoiding Ruby hash conditionals in Ruby on Rails

This gets really old:

if params[:teacher] && params[:teacher][:id] ...

so instead, do this:

if params[:teacher].try(:[], :id)

or do it a lot more:

name = params[:company][:owner][:name] if params[:company] and params[:company][:owner] and params[:company][:owner][:name]

turns into:

name = params.try(:[], :company).try(:[], :owner).try(:[], :name)

Yay for Stack Overflow!


Leave a Reply

Your email address will not be published. Required fields are marked *