0

这是我的函数的代码,我在其中调用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_2registration.email。当然,这样做的一种方法是将整个代码编写两次,并由if-elsif语句包围。但我只想知道,是否有更聪明、更优雅的方式来做到这一点?

4

1 回答 1

1

只需将条件添加到 value 中。

:email        => (type==1 ? registration.email_2 :  registration.email),
于 2012-04-10T07:47:27.863 回答