三元运算符

我有一个数组d = ['foo', 'bar', 'baz'] ,并希望将它的元素放在一个由,和最后一个元素分隔的字符串中,这样它就会变成foo, bar and baz

这是我正在尝试做的事情:

 s = '' d.each_with_index { |x,i| s << x s << i < d.length - 1? i == d.length - 2 ? ' and ' : ', ' : '' } 

但是翻译给出了一个错误:

`<': comparison of String with 2 failed (ArgumentError)

但是,它适用于+=而不是<< ,但Ruby Cookbook说:

如果效率对您很重要,那么当您可以将项目附加到现有字符串时,请不要构建新字符串。 [等等] …使用str << var1 << ' ' << var2代替。

在这种情况下,没有+=可能吗?

此外,必须有一个比上面的代码更优雅的方式。

你只是缺少一些括号:

  d = ['foo', 'bar', 'baz'] s = '' d.each_with_index { |x,i| s << x s << (i < d.length - 1? (i == d.length - 2 ? ' and ' : ', ') : '') } 

我找到了

 s << i < d.length - 1? i == d.length - 2 ? ' and ' : ', ' : '' 

难以阅读或维护。

我可能会改成它

 join = case when i < d.length - 2 then ", " when i == d.length - 2 then " and " when i == d.length then "" end s << join 

或者可能

 earlier_elements = d[0..-2].join(", ") s = [earlier_elements, d[-1..-1]].join(" and ") 

要么

 joins = [", "] * (d.length - 2) + [" and "] s = d.zip(joins).map(&:join).join 

这样简单得多:

 "#{d[0...-1].join(", ")} and #{d.last}"