在Ruby中有一种优雅的方法吗?

时间:2016-01-25 15:37:27

标签: ruby

我想要一个算法来正确设置首选名称。这将是用户的偏好。用户可以在社交名称和民用名称之间进行选择。其中只有一个是强制性的,但如果是nil,我想选择另一个。

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

3 个答案:

答案 0 :(得分:5)

强调用户选择的另一种方式。

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

该示例使用nil评估为false的Ruby属性。因此,nil?检查可以替换为||

答案 1 :(得分:2)

更容易理解代码:

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

为了清晰起见,我添加了返回语句,尽管不需要它们。

答案 2 :(得分:1)

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