如何实现Ruby实用程序类方法?

时间:2014-03-04 18:55:06

标签: ruby rspec

需要帮助实现Ruby 实用程序类方法才能通过此测试。有人可以帮我解决这个问题吗?

我的代码

class Temperature

  class << self
    def from_fahrenheit temp
      Temperature.new({f: temp})
    end

    def from_celsius temp
      Temperature.new({c: temp})
    end
  end

  def initialize(options={})
    @f = options[:f]
    @c = options[:c]
  end

  def in_fahrenheit
    return @f if @f
    (@c * (9.0 / 5.0)) + 32
  end

  def in_celsius
    return @c if @c
    (@f - 32) * 5.0 / 9.0
  end
end

class Celsius < Temperature
  def initialize temp
    @temp = temp
  end
end

class Fahrenheit < Temperature
  def initialize temp
    @temp = temp
  end
end

故障:

  1) Temperature Temperature subclasses Celsius subclass is constructed in degrees celsius
     Failure/Error: (@f - 32) * 5.0 / 9.0
     NoMethodError:
       undefined method `-' for nil:NilClass
     # ./ct.rb:1118:in `in_celsius'
     # ./ct.rb:1219:in `block (4 levels) in <top (required)>'

  2) Temperature Temperature subclasses Fahrenheit subclass is constructed in degrees fahrenheit
     Failure/Error: (@c * (9.0 / 5.0)) + 32
     NoMethodError:
       undefined method `*' for nil:NilClass
     # ./ct.rb:1113:in `in_fahrenheit'
     # ./ct.rb:1230:in `block (4 levels) in <top (required)>'

Rspec测试

 describe "utility class methods" do

  end

  # Here's another way to solve the problem!
  describe "Temperature subclasses" do
    describe "Celsius subclass" do
      it "is constructed in degrees celsius" do
        Celsius.new(50).in_celsius.should == 50
        Celsius.new(50).in_fahrenheit.should == 122
      end

      it "is a Temperature subclass" do
        Celsius.new(0).should be_a(Temperature)
      end
    end

    describe "Fahrenheit subclass" do
      it "is constructed in degrees fahrenheit" do
        Fahrenheit.new(50).in_fahrenheit.should == 50
        Fahrenheit.new(50).in_celsius.should == 10
      end

      it "is a Temperature subclass" do
        Fahrenheit.new(0).should be_a(Temperature)
      end
    end
  end

end

1 个答案:

答案 0 :(得分:0)

您没有使用Temperature类如何定义它。您在options类中使用:f:c个密钥获取Temperature哈希值,但不要在子类中设置这些哈希值。

试试这个:

class Celsius < Temperature
  def initialize temp
    super(c: temp)
  end
end

class Fahrenheit < Temperature
  def initialize temp
    super(f: temp)
  end
end

这是锻炼还是其他什么?这是一个......有趣的设计。