Firice Nguyen Firice Nguyen - 3 months ago 8
Ruby Question

Refactor with loop

I have 2 snippets that need to be refactored

First Block



if condition
array.each do |a|
... # 1st block
var1 = ClassA.new.methodA
... # 2nd block
end
else
array.each do |a|
... # 1st block
var1 = ClassB.new.methodB
... # 2nd block
end


I know that I can reduce this into

array.each do |a|
... # 1st block
var1 = condition ? ClassA.new.methodA : ClassB.new.methodB
... # 2nd block
end


But this array is quite big (roughly 10,000), so it has to do the
condition
check many time with each element. Does anybody know the most elegant way to refactor this?

Second Block



var1 = method1(array.first)
array.[1..-1].each #Loop from 2nd to last element
var1 = var1 + method1(a)
end

ClassA(var1)


With this one I have to initialized the variable with the first array element as the parameter. (
method1
represents a long chain ActiveRecord scope)

These are minor but I am a beginner with Ruby, and I think it's better to inspect more way to have fun with Ruby.

Thank you in advance

Answer

1

λ = condition ? ClassA.new.method(:methodA) : ClassB.new.method(:methodB)
array.each do |a|
  ... # 1st block
  var1 = λ.(a)
  ... # 2nd block
end

Sidenote: ternary operator is not worth such a refactoring; it’s impact on productivity is zero. Class instance creation, on the other hand, worth it.

2

var1 = array.reduce { |memo, e| memo + method1(e) }
Comments