Last active
December 10, 2015 16:28
-
-
Save eriktrautman/4460829 to your computer and use it in GitHub Desktop.
Instance variable scope within a subclass in Ruby... super works to instantiate the subclasses properly but not the factory methods from the Temperature class!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The subclasses really aren't pretty... I had major issues with | |
# getting the subclasses access to the instance variables @c and | |
# @f so they could run the in_celsius and in_fahrenheit methods. | |
class Temperature | |
def initialize t | |
@f = t[:f] | |
@c = t[:c] | |
#puts "initialized!!! t = #{t.inspect}, @f is #{@f.inspect} and @c is #{@c.inspect}" | |
end | |
def in_celsius | |
@c ? @c : ( @f - 32 ) * 5.0 / 9.0 | |
end | |
def in_fahrenheit | |
@f ? @f : @c * 9.0 / 5.0 + 32 | |
end | |
def self.from_celsius c | |
Temperature.new(:c => c) | |
end | |
def self.from_fahrenheit f | |
Temperature.new(:f => f) | |
end | |
end | |
class Celsius < Temperature | |
def initialize t | |
super(:c=>t) | |
end | |
end | |
class Fahrenheit < Temperature | |
def initialize t | |
Temperature::from_fahrenheit(t) | |
# at this point, @c and @f are both back to being nil! | |
@f = t | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment