Reputation: 1016
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
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
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
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