function strjoin(delimiter, list)
local len = getn(list)
if len == 0 then
return ""
end
local string = list[1]
for i = 2, len do
string = string .. delimiter .. list[i]
end
return string
end
strjoin("and ", {"Mario", "Luigi", "Megatron", "Dan Quale"}) –> Mario and Luigi and Megatron and Dan Quale
cur = get_from_iterator()
if cur is null:
return ""
else:
result = cur
while cur = get_from_iterator() is not null:
result = result + delim + cur
That's going to return "1 2 3"
So my question is what's the best practice for implementing this functionality? There's some obvious but inelegant ways. For example you can iterate over a collection and concat the spacer on each pass except on the final pass. This usually requires an if statement and more importantly a way to know you're on the final pass of iteration. Another way is for n elements only iterating over n-1 elements. Then using a special case for the final element. This avoids using an if statement, but at best it seems dirty. These two examples:
Contrived examples, but if someone has something better please share. :p
edit: p.s. just looking for algorithm, doesn't need to be ruby specific.