这是我的函数的代码,我在其中调用new
def create_person_detail_from_registration(type, registration, registration_detail)
person_detail = type.constantize.new(
:email => registration.email_2,
:phone_1 => registration_detail.phone_1,
:phone_2 => registration_detail.phone_2,
:phone_3 => registration_detail.phone_3,
:phone_4 => registration_detail.phone_4,
:phone_5 => registration_detail.phone_5,
:phone_6 => registration_detail.phone_6,
:phone_7 => registration_detail.phone_7,
:address_1 => registration_detail.address_1,
:address_2 => registration_detail.address_2,
:city => registration_detail.city,
:state => registration_detail.state,
:postal_code => registration_detail.postal_code,
:country => registration_detail.country
)
return person_detail
end
现在问题取决于type
的价值,:email
设置为registration.email_2
或registration.email
。当然,一种方法是将if-elsif
语句包围的整个代码编写两次。但我只想知道,如果有更聪明,更优雅的方式吗?
答案 0 :(得分:0)
只需将条件添加到值中即可。
:email => (type==1 ? registration.email_2 : registration.email),