I have an array d = ['foo', 'bar', 'baz'], and want to put its elements together into a string delimited by , and and at the last element so that it will become foo, bar and baz.
Here is what I’m trying to do:
s = ''
d.each_with_index { |x,i|
s << x
s << i < d.length - 1? i == d.length - 2 ? ' and ' : ', ' : ''
}
but the interpreter gives an error:
`<': comparison of String with 2 failed (ArgumentError)
However, it works with += instead of <<, but the Ruby Cookbook says that:
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 << ' ' << var2instead.
Is it possible without += in this case?
Also, there has to be a more elegant way of doing this than the code above.
You’re just missing some parenthesis: