相关疑难解决方法(0)

三元运算符

我有一个数组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 ' : ', ' : ''
}
Run Code Online (Sandbox Code Playgroud)

但是解释器给出了一个错误:

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

但是,它可以+=代替<<,但Ruby Cookbook说:

如果效率对您很重要,则在将项目附加到现有字符串时不要构建新字符串.[等等] ......请str << var1 << ' ' << var2改用.

+=在这种情况下是否可能?

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

ruby conditional-operator

1
推荐指数
1
解决办法
694
查看次数

标签 统计

conditional-operator ×1

ruby ×1