简体   繁体   English

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

[英]NoMethodError: undefined method `[]=' for nil:NilClass

Error in title.标题错误。 What's going wrong?怎么了? Attempting to initialize Temperature object with a hash.试图用散列初始化温度对象。 If I just do如果我只是这样做

puts Temperature.from_celsius(50).in_fahrenheit

then it works fine and returns 122.0然后它工作正常并返回 122.0

But

Temperature.new(:f => 50)

returns an error.返回错误。

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

Just as the error message says.正如错误消息所说。 You are calling []= on @temp in a Temperature instance, which is nil by default because you have not assigned anything to it anywhere.您正在Temperature实例中对@temp调用[]= ,默认情况下nil ,因为您没有在任何地方为其分配任何内容。

You can't initialize instance variable in a class body, as you did.您不能像以前那样在类体中初始化实例变量。 You should do it in a constructor, and because you have three constructors, your code should look like this:您应该在构造函数中执行此操作,因为您有三个构造函数,您的代码应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM