NoMethodError:未定义的方法`[] ='为nil:NilClass

时间:2014-08-01 10:44:10

标签: ruby

标题错误。出了什么问题? 尝试使用哈希初始化Temperature对象。如果我只是做

puts Temperature.from_celsius(50).in_fahrenheit

然后它工作正常并返回122.0

但是

Temperature.new(:f => 50)

返回错误。

class Temperature
  attr_accessor :f, :c

  @temp = {:f => 32, :c => 0}

  def initialize(params)
    if params[:f] != nil
      self.class.from_fahrenheit(params[:f])

    else 
      self.class.from_celsius(params[:c])
    end
  end

  def self.from_fahrenheit(temp)
   @temp[:f] = temp 
   @temp[:c] = ((temp - 32.0)/1.8).round(1)

    return @temp
  end

  def self.from_celsius(temp)
    @temp[:c] = temp
    @temp[:f] = (temp * 1.8 + 32).round(1)

    return @temp
  end  

  def in_fahrenheit
    @temp[:f]
  end

  def in_celsius
    @temp[:c]
  end


end

class Hash
  def in_fahrenheit
    self[:f]
  end

  def in_celsius
    self[:c]
  end
end

puts Temperature.from_celsius(50).in_celsius

tempo = Temperature.new(:f => 50)
tempo.in_fahrenheit

2 个答案:

答案 0 :(得分:1)

正如错误消息所示。您在[]=实例@temp上呼叫Temperature,默认情况下为nil,因为您尚未在任何地方为其分配任何内容。

答案 1 :(得分:1)

您不能像处理那样在类体中初始化实例变量。您应该在构造函数中执行此操作,并且因为您有三个构造函数,所以您的代码应如下所示:

class Temperature
  def initialize(params)
    @temp = {:f => 32, :c => 0}
    if params[:f] != nil
      self.class.from_fahrenheit(params[:f])
    else 
      self.class.from_celsius(params[:c])
    end
  end

  def self.from_fahrenheit(temp)
    @temp = {}
    @temp[:f] = temp 
    @temp[:c] = ((temp - 32.0)/1.8).round(1)

    return @temp
  end

  def self.from_celsius(temp)
    @temp = {}
    @temp[:c] = temp
    @temp[:f] = (temp * 1.8 + 32).round(1)

    return @temp
  end  

  def in_fahrenheit
    @temp[:f]
  end

  def in_celsius
    @temp[:c]
  end


end
相关问题