Is there a way to make this one liner better looking?
@var = params[:key1][:key2] unless params.blank? || params[:key1].blank?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Wow, thanks for all the replies!
I’m going to sum up the answers – as the answer seems more subtle than just another oneliner 😉
As gertas point out that params is always present in a controller action (which is indeed where I’m working), and that nil check is enough, my original code can thus be reduced to:
This is quite readable but not as short as other suggestions, like
or even
I wondered how to use rubys try() method on hashes, and hellvinz gave the answer (rewritten to match my new/realized need):
Finally, Shinya Miyazaki came up with some interesting variations using fetch and merge:
I ended up going with “my own”, to honor the principle of “Clarity over Brevity” as pointed out by Chris McCauley
Thanks again everyone! 🙂