【主因】使用 attr_reader 方法比起直接用 實體變數 好抓錯
# ===用實體變數拼錯字時會出現===
Failure/Error: (@widt * length + length * height + width * height) * 2
NoMethodError: undefined method `*' for nil:NilClass
# ===用 attr_reader 方法拼錯字時會出現===
Failure/Error: (widt * length + length * height + width * height) * 2
NameError: undefined local variable or method `widt' for #<Block:0x00007f9d2d4106c8 @width=2, @length=2, @height=2>
Did you mean? width
@width
【小結】很明顯看得出來,運用 attr_reader 的方法噴錯時,ruby 會很明確地告訴你那邊有問題,甚至提示你可能的正確寫法。用實體變數則只告訴你 nil,但我們還是不知道問題錯在哪
# 實作以下內容
class Block
# 實作內容
end
RSpec.describe do
it "實作內容" do
cube = Block.new([2,2,2])
expect(cube.width).to be 2
expect(cube.length).to be 2
expect(cube.height).to be 2
expect(cube.volume).to be 8
expect(cube.surface_area).to be 24
end
end
class Block
def initialize(array)
@array = array
end
def width
@array[0]
end
def length
@array[1]
end
def height
@array[2]
end
def volume
@array.reduce(1) { |start, i| start * i }
end
def surface_area
@array[0] * @array[1] * 6
end
end
class Block
attr_reader :width, :length, :height
def initialize(array)
@width, @length, @height = array
end
def volume
width * length * height
end
def surface_area
(width * length + length * height + width * height) * 2
end
end