Skip to content

Instantly share code, notes, and snippets.

@eriktrautman
Last active December 10, 2015 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eriktrautman/4460829 to your computer and use it in GitHub Desktop.
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!
# 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