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

如何实现Ruby实用程序类方法?,ruby,rspec,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(optio

需要帮助实现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

您没有使用定义温度的
类。在
Temperature
类中,使用
:f
:c
键进行
options
散列,但不在子类中设置它们

试试这个:

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

class Fahrenheit < Temperature
  def initialize temp
    super(f: temp)
  end
end
class摄氏度<温度
def初始化温度
超级(c:temp)
终止
终止
华氏级<温度
def初始化温度
超级(f:temp)
终止
终止

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

是的,这是一个练习。是否需要调用超级
super
?看看我的答案。它还通过了Rspec测试。“有趣”是指可怕的吗?因为我承认我写这段代码时并不了解它是如何工作的。我在学习ruby,我把这个练习的结果归因于潜意识编码。好吧,
Temperature
通过使用选项散列定义了一个接口,在你的子类中,你绕过它,进入那个类并设置它的变量。您的解决方案最终使用了两种不同的方法初始化
@f
@c
变量,这有点混乱,而且容易出错。这一切都取决于这是否重要正如我所理解的,通过在子类中使用
super
,我正在访问
f
c
Temperature
类中初始化的值。没有使用
super
(如我下面的答案所示),我绕过
Temperature
类中的初始化值,只是分别在
摄氏度
华氏度
类中设置它们?
 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
class Celsius < Temperature
  def initialize temp
    super(c: temp)
  end
end

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