cresjoy cresjoy - 5 months ago 13
Ruby Question

Understanding Flattening array in ruby

I think i'm a bit confused with what .each_with_object does to an extent.
For example

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


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

Now even after reading the example on ruby documentation, I am a bit
confused as to what the parameter inside
object()
, actually does. Also to my understanding. I was particularly confused as well with the usage of * here. and why our else statement is just
element
. What is
element
intended to do in this piece of code?

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.