2013-08-27 35 views
1

我正在計算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)>' 
+1

對於像這樣的事情,您應該真正以°C或°K爲單位進行存儲,因爲這些都是在科學環境中使用的。 °F是主要由美國人和其他人使用的時代錯誤。 – tadman

+1

當°F - >°C轉換是一個簡單的線性方程時,您也有很多奇怪的例子:「°C =(°F - 32)*(5/9)」還請注意您的測試覆蓋面非常薄,您應該測試至少一打隨機點以確保您獲得正確的值。 – tadman

+0

這只是混亂。 '溫度。新(f:20).to_fahrenheit'返回'50'? – tadman

回答

4

在你的初始化方法,你覆蓋散列傳遞給函數。

def initialize(f) 
     f = Hash.new 
     @f = f 
    end 

應該像

def initialize(f={}) 
     @f = f 
    end 
+0

你是對的.. :)我實際上是在尋找OP在哪裏錯過了'@ f' ..那是我找到的地方..並且錯誤地給了一個不好的答案..但是你應該有你的* + 1 * .. –

1

您重複的變量f很多在你的代碼,我認爲這是造成你的問題。

您正在命名傳遞給構造函數f的變量,然後爲其分配一個新的空白哈希。這將您的本地attr_accessor :f@f設置爲新的散列。

然後,您將重新指定您的本地f在用f = value.to_f進行計算的塊中,而您實際上是通過f循環的。

您需要解決構造函數重新分配問題,然後爲您的value.to_f轉換使用不同的局部變量名稱。

+0

「這將您的本地attr_accessor:f或@f設置爲新的散列。「不,'f = Hash.new'不會調用'f ='訪問器函數。它創建一個名爲'f'的局部變量。要調用存取函數,他需要調用'self.f = Hash.new'。然而,在下一行,他做了@f = f,他確實設置了@ f來表示空的散列。 – sepp2k