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

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -