Ruby NoMethodError:未定义的方法“[]=';零级:零级
标题错误。怎么了? 正在尝试使用散列初始化温度对象。如果我这么做的话Ruby NoMethodError:未定义的方法“[]=';零级:零级,ruby,Ruby,标题错误。怎么了? 正在尝试使用散列初始化温度对象。如果我这么做的话 puts Temperature.from_celsius(50).in_fahrenheit 然后它工作正常,返回122.0 但是 返回一个错误 class Temperature attr_accessor :f, :c @temp = {:f => 32, :c => 0} def initialize(params) if params[:f] != nil self.
puts Temperature.from_celsius(50).in_fahrenheit
然后它工作正常,返回122.0
但是
返回一个错误
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
正如错误消息所说。您在
温度实例中调用[]=
的@temp
,该实例默认为nil
,因为您没有在任何地方分配任何内容。您不能像以前那样初始化类主体中的实例变量。您应该在构造函数中执行此操作,因为您有三个构造函数,所以您的代码应该如下所示:
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
您的短语“类实例”不清楚。你是指一个类的实例,还是指某个类的实例?如果是后者,那么你的描述就有误导性。但是我的第四行是@temp={:f=>32,:c=>0}
@temp已初始化。我仍然很困惑。您为Temperature
类初始化了它,但不是为它的实例初始化的。我认为@variablename使它成为一个实例变量。我对范围的理解正在崩溃。注意,类也是(类的)一个实例。您为类
类(温度
)的实例创建了一个实例变量,但没有为类
类的该实例创建实例变量。这很有意义。非常感谢。
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