cresjoy cresjoy - 1 year ago 70
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"

(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
, actually does. Also to my understanding. I was particularly confused as well with the usage of * here. and why our else statement is just
. What is
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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download