gpt4 book ai didi

ruby - 无方法错误 : undefined method `[]=' for nil:NilClass

转载 作者:太空宇宙 更新时间:2023-11-03 16:01:04 24 4
gpt4 key购买 nike

标题错误。出了什么问题?试图用散列初始化 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

最佳答案

正如错误信息所说。您正在 Temperature 实例中的 @temp 上调用 []=,默认情况下为 nil,因为您有没有在任何地方分配任何东西。

关于ruby - 无方法错误 : undefined method `[]=' for nil:NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25078493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com