I want to process the array ['a', 'b', 'c']
to return the string '0a1b2c'
(i.e, string formed by concatenating each index with its value).
I can do this:
result = ''
['a', 'b', 'c'].each.with_index do |char, i|
result += "#{i}#{char}"
end
result
I want to eliminate the result variable outside the block by using with_object.
Something like this:
['a', 'b', 'c'].each.with_index.with_object('') do |char, i, result|
result += "#{i}#{char}"
end
But this raises an error undefined method '+' for nil:NilClass
It doesn't use the methods you ask for, but it does the job and is relatively compact :