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?
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"]]
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"]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With