using rescue in variable assignment

196 views Asked by At

I have this

User.new ( gender: auth.extra.raw_info.gender.capitalize, ...)

auth is a hash that looks like this

auth => {:extra => { :raw_info => { :gender => ... , .. }, ..} ..}

sometimes, for whatever reason, the gender doesn't exist and I want to have a default value for it when I create a new user

If I try

gender: auth.extra.raw_info.gender.try(:capitalize) || "Male"

but the gender itself doesn't exist, and I can't try on gender

using gender: auth.extra.raw_info.gender.capitalize rescue "Male"

also doesn't work since it says I can't use capitalize on nil (which is gender)

Is there a way to do this without using a variable for this (since it will become messier)

1

There are 1 answers

2
Yanhao On BEST ANSWER

I think the standard way to do this is to use reverse_merge:

auth.reverse_merge! {:extra => { :raw_info => { :gender => "Male" } } }