Donato Donato - 1 year ago 90
Ruby Question

flat_map in ruby when working with different elements

I think flat_map is great when you have an array of hashes of variable lengths and you want to work with each one individually:

data = [
{'apple' => 'fruit'},
{'carrot' => 'vegetable'},
{'orange' => 'fruit', 'pear' => 'fruit'},
{'lettuce' => 'vegetable'}

data.flat_map(&:to_a).reduce([]) {|acc, (k,v)| acc << Hash[k,v] }
=> [{"apple"=>"fruit"}, {"carrot"=>"vegetable"}, {"orange"=>"fruit"}, {"pear"=>"fruit"}, {"lettuce"=>"vegetable"}]

But I don't think I fully understand flat_map. According to docs:

Returns a new array with the concatenated results of running block
once for every element in enum.

But look at this example:

[[1], {a: "a"}, {b: "b"}].flat_map(&:to_a)
=> [1, [:a, "a"], [:b, "b"]]

The first item is stripped from the inner array, the other items are converted to arrays. How does it know to do this?

When I call to_a like this:

=> [1]
=> [1]

You see the result is different than what flat_map did. What is flat_map doing in the first example to strip the item of the array?

Answer Source

For any array arr having m+n elements, if { ... }


[a1, a2,.., am, o1, o2,.., on]

where a1, a2,.., am are are arrays and o1, o2,.., on are objects other than arrays, then by changing map to flat_map, leaving the block unchanged, flat_map will return

[*a1, *a2,.., *am, o1, o2,.., on]

Example 1


arr = [[1], {a: "a"}, {b: "b"}]

we have
  #=> [[1], [[:a, "a"]], [[:b, "b"]]]

so it follows that


will return

[*[1], *[[:a, "a"]], *[[:b, "b"]]]
  #=> [1, [:a, "a"], [:b, "b"]] 

and indeed it does.

Example 2

Suppose now that we have

arr = [1, 'cat', [2,3], {a: 4}]

  #=> [1, "cat", [2, 3], {:a=>4}]



is found to return

[1, "cat", 2, 3, {:a=>4}]

which is the reduction of

[1, "cat", *[2, 3], {:a=>4}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download