Hi all.
I have read activesupport module and found little issue.
class Array
current behaviour
def split(value = nil)
if block_given?
inject([]) do |results, element|
if yield(element)
results <<
else
results.last << element
end
results
end
else
results, arr = [], self.dup
until arr.empty?
if (idx = arr.index(value))
results.last.concat(arr.shift(idx))
arr.shift
results <<
else
results.last.concat(arr.shift(arr.size))
end
end
results
end
end
proposed behaviour
def split2(value = nil)
if block_given?
inject([]) do |results, element|
if yield(element)
results <<
else
results.last << element
end
results
end
else
(idx = index(value)) ? [first(idx), last(size-idx-1)] : [self]
end
end
end
arr = (1…12).to_a
Benchmark.ips do |x|
x.report(‘before’) { arr.split(3) }
x.report(‘after’) { arr.split2(3) }
end
Calculating -------------------------------------
before 42.191k i/100ms
after 92.326k i/100ms