scribble

吕小荣

Blog Friends RSS About

Using try method to check existence of key in hash

Published on 2013-11-03

Parameter is a hash, frequently used to transfer data. Sometimes it nests as the following structure:


:user => {:name => "Ryan", :sex => "male", :age => "28"}

To access ‘:name’ in your controller, you probably write code like this:


def name
	params[:user][:name]
end

Wait! Something is wrong. Rails will raise undefined method[:name] for nil error when param[:user] doesn’t exit

Sadly, you have to clutter your code to make it work.


def name
	params[:user] ? params[:user][:name] : nil
end

Actually, you have another choice - try method. Code can also be writen as


def name
	params[:user].try(:[], :name)
end

Now it works perfectly and clean.

Look up .try method of Rails.


吕小荣 at 00:00
Edit this page