根据Ruby中的条件将不同的参数传递给方法调用

时间:2012-04-10 07:41:11

标签: ruby-on-rails ruby

这是我的函数的代码,我在其中调用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语句包围的整个代码编写两次。但我只想知道,如果有更聪明,更优雅的方式吗?

1 个答案:

答案 0 :(得分:0)

只需将条件添加到值中即可。

:email        => (type==1 ? registration.email_2 :  registration.email),