I have a collection which, after the code has ran, looks something like the following:
[
{ title: 'alpha', lines: [ { *some object* } ] },
{ title: 'bravo', lines: [ { *some object* } ] },
{ title: 'charl', lines: [ { *some object* } ] },
{ title: 'delta', lines: [ { *some object*, *some object 2*, *some object 3* } ] m},
{ title: 'echoo', lines: [ { *some object* } ] },
]
The way that I'm doing this is:
- Check if there is an object in the outer array that has a matching
title
- If it doesn't exist, create that object with the
title
andlines
- If it doesn't exist, create that object with the
- Check if inside
lines
there is an object that exists at the specific supplied index- If it doesn't exist, create the object at that index
- Otherwise take the existing object at that index and append
val
toa_or_b
This method will get called multiple times per group i.e. 4 times for alpha
, 4 times for bravo
, and 4 times for each line in delta
. There is currently one group (but there may be more in the future) which has more than one object inside the lines
.
def data_with(data, val, group, date, nom, a_or_b, line_no = 0)
# add this group if it doesn't exist
if data.find { |x| x[:title] == group }.nil?
data << { title: group, lines: [] }
end
# if the line at the line_no doesn't exist, create it
if data.find { |x| x[:title] == group }[:lines][line_no].nil?
data.find { |x| x[:title] == group }[:lines][line_no] = {
date: date,
nom: nom,
a_or_b.to_sym => val
}
else # add to the value of the line at the line_no index
data.find { |x| x[:title] == group }[:lines][line_no][a_or_b.to_sym] += val
end
end
What are some ways I can improve this method?