我有一个数组 d = ['foo', 'bar', 'baz']
, 并希望将其元素组合成一个由 ,
分隔的字符串和 and
在最后一个元素,这样它将变成 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 说:
If efficiency is important to you, don't build a new string when you can append items onto an existing string. [And so on]... Use
str << var1 << ' ' << var2
instead.
没有+=
是否可行在这种情况下?
此外,必须有一种比上面的代码更优雅的方法。
最佳答案
你只是少了一些括号:
d = ['foo', 'bar', 'baz']
s = ''
d.each_with_index { |x,i|
s << x
s << (i < d.length - 1? (i == d.length - 2 ? ' and ' : ', ') : '')
}
关于ruby - 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548030/