bpereira
bpereira

Reputation: 1016

Is there an elegant way to do this in Ruby?

I want an algorithm to set the preferred name correctly. It will be the preference of the user. The user can choose between the social name and the civil name. Only one of those is mandatory, but if it's nil, I want to pick the other one.

if name_preference == SOCIAL_NAME_PREFERENCE && !social_name.nil? || name_preference == CIVIL_NAME_PREFERENCE && civil_name.nil?
  social_name
elsif name_preference == CIVIL_NAME_PREFERENCE && !civil_name.nil? || name_preference == SOCIAL_NAME_PREFERENCE && social_name.nil?
  civil_name
end

Upvotes: 1

Views: 99

Answers (3)

sschmeck
sschmeck

Reputation: 7713

Another way to emphasize the choice of the user.

if name_preference == CIVIL_NAME_PREFERENCE
  civil_name || social_name 
elsif name_preference == SOCIAL_NAME_PREFERENCE
  social_name || civil_name
end

The example uses the Ruby property that nil evaluates to false. Therefore the nil? check can replaced by ||.

Upvotes: 5

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71019

Much easier to understand code:

if name_preference == CIVIL_NAME_PREFERENCE
   return civil_name.nil? ? social_name : civil_name
elsif name_preference == SOCIAL_NAME_PREFERENCE
   return social_name.nil? ? civil_name : social_name
end

I added the return statements for clarity though they are not needed.

Upvotes: 2

sawa
sawa

Reputation: 168269

case name_preference
when SOCIAL_NAME_PREFERENCE
 social_name.nil? ? civil_name : social_name
when CIVIL_NAME_PREFERENCE
 civil_name.nil? ? social_name : civil_name
end

Upvotes: 1

Related Questions