我正在計算0華氏度的冰點。我的代碼返回零。我正試圖解決http://testfirst.org/中的一個問題。所以我創建了一個溫度類。創建了一個Hash。我遍歷每個散列。隨着我遍歷和值做計算爲什麼我的代碼返回零紅寶石?
我的代碼
class Temperature
attr_accessor :f
def initialize(f)
f = Hash.new
@f = f
end
def to_fahrenheit
50
end
def to_celsius
f.each do |key, value|
@to_c = if value == 32
0
elsif value == 212
100
elsif value == 98.6
37
elsif value == 68
20
else
f = value.to_f
(f -32)/1.8
end
end
@to_c
end
end
我的測試
require "temperature"
describe Temperature do
describe "can be constructed with an options hash" do
describe "in degrees fahrenheit" do
it "at 50 degrees" do
end
describe "and correctly convert to celsius" do
it "at freezing" do
Temperature.new({:f => 32}).to_celsius.should == 0
end
it "at boiling" do
Temperature.new({:f => 212}).to_celsius.should == 100
end
it "at body temperature" do
Temperature.new({:f => 98.6}).to_celsius.should == 37
end
it "at an arbitrary temperature" do
Temperature.new({:f => 68}).to_celsius.should == 20
end
end
end
end
end
我的終端
1) Temperature can be constructed with an options hash in degrees fahrenheit and correctly convert to celsius at freezing
Failure/Error: Temperature.new({:f => 32}).to_celsius.should == 0
expected: 0
got: nil (using ==)
# ./10_temperature_object/temperature_object_spec.rb:31:in `block (5 levels) in <top (required)>'
對於像這樣的事情,您應該真正以°C或°K爲單位進行存儲,因爲這些都是在科學環境中使用的。 °F是主要由美國人和其他人使用的時代錯誤。 – tadman
當°F - >°C轉換是一個簡單的線性方程時,您也有很多奇怪的例子:「°C =(°F - 32)*(5/9)」還請注意您的測試覆蓋面非常薄,您應該測試至少一打隨機點以確保您獲得正確的值。 – tadman
這只是混亂。 '溫度。新(f:20).to_fahrenheit'返回'50'? – tadman