Ruby连接最佳实践

时间:2013-07-23 15:37:26

标签: ruby

我需要在Ruby中解决一个简单的问题,但希望以一种聪明的方式来解决它。我有一个功能:

def fullname
  first + " " + mi + last
end

如果一个或多个变量为nil,那将会崩溃,让我们说这个例子的mi,因为它在中心。

错误:

  

无法将nil转换为String

如果我将功能更改为:

def fullname
  first + " " + mi.to_s + last
end

def fullname
  first + " " + (mi || "") + last
end

它会修复它。现在我想在mi(中间首字母)之后添加一个额外的空格(如果它存在)并且我为了一些愚蠢的理由而难以接受。做这样的事最干净的方法是什么,因为我将不得不做很多事情,有时还会加上逗号。

需要的例子:

def fullname
  first + " " + (mi || "") + last + suffix 
  # want a ", " afer the last name if there is a suffix
end

3 个答案:

答案 0 :(得分:8)

首先:我实际上会说处理这种问题的最“Ruby”方式 - 避免nil问题,就是使用字符串插值

"#{first} #{mi} #{last}"

如果以上任何变量都是nil,这样就可以了,因为它只会导致字符串中的空格。

关于条件空间问题:有很多方法可以让那只猫受到伤害。我非常喜欢sawa's idea。这是另一个,我见过它的变体,虽然它不是特别有效(但是10次中有9次并不重要):

[first, mi, last].compact.join(" ")

最后:对于“加号逗号+后缀(如果存在)”要求,这很复杂,我建议写一个小方法来分离逻辑:

def suffix_if_necessary(name)
  suffix ? "#{name}, #{suffix}" : name
end

def fullname
  suffix_if_necessary([first, *mi, last].join(" "))
end

但同样,有很多方法可以在这里完成工作。什么对你有用。

答案 1 :(得分:7)

def fullname
  [[first, *mi, last].join(" "), *suffix].join(", ")
end

答案 2 :(得分:1)

我建议您使用字符串插值来清楚地表明您从该方法返回一个字符串(并且还会忽略nil个值):

def fullname
    s = "#{first} #{mi} #{last}".lstrip.rstrip.squeeze(' ')
    s += ", #{suffix}" if suffix
end
相关问题