为什么我的代码在ruby中返回nil?

时间:2013-08-27 18:50:33

标签: ruby-on-rails ruby hash

我正在尝试计算0华氏度的冰点。我的代码返回零。我想在http://testfirst.org/中解决一个问题。所以我创建了一个Temperature类。创造了一个哈希。我遍历每个哈希。使用值I迭代并进行计算

我的代码

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)>'

2 个答案:

答案 0 :(得分:4)

在initialize方法中,您将覆盖传递给函数的哈希值。

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

应该是

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

答案 1 :(得分:1)

您在代码中重复使用了变量f,我认为这会导致您的问题。

您正在命名传递给构造函数f的变量,然后为其分配一个新的空哈希。这会将您的本地attr_accessor :f@f设置为新的哈希值。

然后,当您实际循环f时,您将在使用f = value.to_f进行计算的块中重新分配本地f

您需要解决构造函数重新分配问题,然后使用其他本地变量名称进行value.to_f转换。