I am having problems refactoring out some duplicated code from two methods sharing a for loop. The two methods with the duplicated code are gcdOfFiveUpToFive and remainderStepsUpToFive. The two loops share in common setting instance variable @m to 5 and the both use a for x in 1..5 loop and then set @n to x as well as both of them need to call euclidGCD although one calls euclidGCD for its return value and the other to add +=1 to the @count variable. I do want want to return 2 values from one method. I guess I could make a 4th instance variable called @countArray and get an array of the remainder step count.
require 'minitest/autorun'
class GCDTest < Minitest::Test
def test_euclid_gcd
gcdTestObject=GCD.new(20,5)
assert gcdTestObject.euclidGcd==5
assert gcdTestObject.gcdRemainderSteps==1
end
def test_euclid_two
gcdTestObject=GCD.new(13,8)
assert gcdTestObject.euclidGcd==1
assert gcdTestObject.gcdRemainderSteps==5
end
def test_euclid_loop
gcdTestObject=GCD.new(0,0)
assert gcdTestObject.gcdOfFiveUpToFive==[1,1,1,1,5]
end
def test_count_of_loop
gcdTestObject=GCD.new(0,0)
assert gcdTestObject.remainderStepsUpToFive==[1,2,3,2,1]
end
end
class GCD
attr_accessor :m,:n
attr_reader :count
def initialize(m,n)
@m=m
@n=n
@count=0
end
def euclidGcd
@count=1
m=@m
n=@n
r= m % n
until r==0
m=n
n=r
r= m % n
@count+=1
end
return n
end
def gcdRemainderSteps
return @count
end
def gcdOfFiveUpToFive
@m=5
gcdArrayUpToFive=[]
for x in 1..5
@n=x
gcdArrayUpToFive << euclidGcd
end
return gcdArrayUpToFive
end
def remainderStepsUpToFive
@m=5
gcdStepArrayUpToFive=[]
for x in 1..5
@n=x
euclidGcd
gcdStepArrayUpToFive << gcdRemainderSteps
end
return gcdStepArrayUpToFive
end
def fiveLoopExtraction
end