Given
a = nil # or [1,2]
b = [1,2] # or nil
Can you iterate through the concatenation of a and b without allocating an intermediate or creating massive amount of boiler plate code?
# meaning do this much more efficiently
((a || []) + (b || [])).each do |thing|
# more lines here
puts thing
end
This is kind of ugly:
l = lambda{|thing| do_my_thing }
a.each{|thing| l.call(thing)} if a
b.each{|thing| l.call(thing)} if b
Well, if you’re willing to create a container (which should be cheap even if the elements contained are large), you could:
You do have to create a container array, but since you don’t have to copy the contents of the sub-arrays (and instead are just dealing with two array pointers), it should be very quick and not terrible on the GC.
An alternate solution might just be to create a method: