i picked tutorials need use initialize. here's portion of code:
class temperature def initialize(c: nil, f: nil) @fahrenheit = f @celsius = c end def in_celsius @celsius ||= (@fahrenheit - 32) * 5.0 / 9 end end here's rspec test:
describe "in degrees celsius" "at 50 degrees" temperature.new(:c => 50).in_celsius.should == 50 end when tests chunk above, value 50 attached key :c. @celsius = c mean c value of :c key? new method automatically direct initialize method?
in ruby .new creates new object , calls .initialize method on object. if there no initialize method declared calls initializer on superclass.
so when call temperature.new(c: 15) pass arguments initialize method:
def initialize(c: nil, f: nil) # arguments in here passed .new @fahrenheit = f # alters temperature instance @celsius = c # alters temperature instance puts self.inspect # show self new temperature instance end on side note:
its not @intialize since @ sign denotes instance variable. initialize method. when writing methods convention write foo#bar instance methods , foo.bar class methods.
Comments
Post a Comment