whi*_*win 1 ruby conditional-operator
我有一个数组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
改用.
+=
在这种情况下是否可能?
此外,必须有一个比上面的代码更优雅的方式.
你只是缺少一些括号:
d = ['foo', 'bar', '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)