Reputation: 82
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
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
Upvotes: 2
Views: 326
Reputation: 2901
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
Upvotes: 1
Reputation: 168071
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.
Upvotes: 1