cresjoy cresjoy - 5 months ago 10
Ruby Question

Understanding flattening an array in Ruby

I'm a confused with what

.each_with_object
does to an extent.

For example:
("a".."c").each_with_object("") {|i,str| str << i} # => "abc"


Also:
(1..3).each_with_object(0) {|i,sum| sum += i} #=> 0
(since integers are immutable).




After reading the example in the Ruby documentation, I'm
confused as to what the parameter inside
object()
actually does.

Regarding the
flattify
code below: I was confused with the usage of
*
; and why is the else statement just
element
? What is
element
intended to do?

def flattify(array)
array.each_with_object([]) do |element, flattened|
flattened.push *(element.is_a?(Array) ? flattify(element) : element)
end
end

Answer

The parameter you pass to object() acts as accumulator for intermediate values between iterations. On entry to each iteration it is passed as flattened argument.

* is a splat operator. It converts an array to a list of arguments being passed to the push method.