ruby - Ternary operator -
i have array d = ['foo', 'bar', 'baz']
, , want put elements string delimited ,
, and
@ last element become foo, bar , baz
.
here i'm trying do:
s = '' d.each_with_index { |x,i| s << x s << < d.length - 1? == d.length - 2 ? ' , ' : ', ' : '' }
but interpreter gives error:
`<': comparison of string 2 failed (argumenterror)
however, works +=
instead of <<
, ruby cookbook says that:
if efficiency important you, don't build new string when can append items onto existing string. [and on]... use
str << var1 << ' ' << var2
instead.
is possible without +=
in case?
also, there has more elegant way of doing code above.
you're missing parenthesis:
d = ['foo', 'bar', 'baz'] s = '' d.each_with_index { |x,i| s << x s << (i < d.length - 1? (i == d.length - 2 ? ' , ' : ', ') : '') }
Comments
Post a Comment