• 하나의 책임만 수행하는 메서드와 클래스로 분리한다.
Example1: Gear class code
Gear class 에서 Wheel class를 분리한다. 먼저 gear_inches method의 연산에서 diameter method를 분리한 후 Wheel class를 만든다.
# chainring(앞 톱니수), cog(뒷 톱니수), rim(바퀴테 지름), tire(타이어 높이)
# ratio(기어비)
class Gear
attr_reader :chainring, :cog, :rim, :tire
def initialize(chainring, cog, rim, tire)
@chainring = chainring
@cog = cog
@rim = rim
@tire = tire
end
def ratio
chainring / cog.to_f
end
def gear_inches
ratio * (rim + (tire * 2))
end
end
puts Gear.new(52, 11).ratio
puts Gear.new(30, 27).ratio
Example 2: Gear and Wheel class
# chainring(앞 톱니수), cog(뒷 톱니수), rim(바퀴테 지름), tire(타이어 높이)
# ratio(기어비)
class Gear
attr_reader :chainring, :cog, :wheel
def initialize(chainring, cog, wheel=nil)
@chainring = chainring
@cog = cog
@wheel = wheel
end
def ratio
chainring / cog.to_f
end
def gear_inches
ratio * wheel.diameter
end
end
class Wheel
attr_reader :rim, :tire
def initialize(rim, tire)
@rim = rim
@tire = tire
end
def diameter
rim + (tire * 2)
end
def circumference
diameter * Math::PI
end
end
@wheel = Wheel.new(26, 1.5)
puts @wheel.circumference
puts Gear.new(52, 11, @wheel).ratio
puts Gear.new(52, 11, @wheel).gear_inches
puts Gear.new(30, 27).ratio