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
Try this
How does this work?
with_indexandwith_objectcreates nested tuples(each, n), objunpacks both tuplesFun fact—or maybe rather sad fact—the nested tuple actually materialized as a short-lived array so this will create
O(n)arrays. If this is a critical production codepath I would away nesting these two enumeration functions. Since you most likely are going to assignobjto a variable in the outer scope anyway it would make most sense to rewrite this as