Saad Rehman Shah
Saad Rehman Shah

Reputation: 946

Passing different parameter to a method call depending on a condition in Ruby

This is the code for my function, in which I am making a call to 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

Now the issue is depending on what value type has, :email is either set to registration.email_2 or registration.email. One way of doing that is of course, to write the whole code twice surrounded by an if-elsif statement. But I just wanna know, if there's any smarter, more elegant way of doing this?

Upvotes: 0

Views: 1549

Answers (1)

Vik
Vik

Reputation: 5961

Just add the condition into value .

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

Upvotes: 1

Related Questions