cresjoy cresjoy - 1 year ago 74
Ruby Question

Understanding flattening an array in Ruby

I'm a confused with what

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).

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

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

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