Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge values from empty rows using Ruby collection functions?

I have a collection:

a = [[1, "a"], [nil, "b"], [nil, "c"], [2, "a"], [nil, "b"]]

[[1, "a"], 
 [nil, "b"], 
 [nil, "c"], 
 [2, "a"], 
 [nil, "b"]] 

and I would like to get:

[[1, "abc"],   
 [2, "ab"]]

What is a proper way to achieve this in Ruby? How can do this effectively using ruby built-in collection functions?

like image 281
Tony Babarino Avatar asked May 13 '26 20:05

Tony Babarino


2 Answers

a
.slice_before{|k, _| k}
.map{|a| [a.first.first, a.map(&:last).join]}
# => [[1, "abc"], [2, "ab"]]

or

a
.slice_before{|k, _| k}
.map{|a| a = a.dup; [a.first.shift, a.join]}
# => [[1, "abc"], [2, "ab"]]
like image 78
sawa Avatar answered May 16 '26 09:05

sawa


 input = [[1, "a"], [nil, "b"], [nil, "c"], [2, "a"], [nil, "b"]]
 input.each_with_object({}) do |(k, v), acc|
   acc[k] = "" if k
   acc.values.last << v
 end.to_a
 #⇒ [[1, "abc"], [2, "ab"]]
like image 24
Aleksei Matiushkin Avatar answered May 16 '26 10:05

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!