ruby - Poking around in parent's internal state -
tl:dr how decoupling work? need little example
i'm reading programming ruby - pragmatic programmer's guide. (http://ruby-doc.org/docs/programmingruby/html/tut_classes.html)
there example on how implement to_s subclass karaokesong of song.
class karaokesong < song # ... def to_s "ks: #{@name}--#{@artist} (#{@duration}) [#{@lyrics}]" end end asong = karaokesong.new("my way", "sinatra", 225, "and now, the...") asong.to_s » "ks: way--sinatra (225) [and now, the...]"
now bad way it:
say decided change song store duration in milliseconds. suddenly, karaokesong start reporting ridiculous values. idea of karaoke version of ``my way'' lasts 3750 minutes frightening consider.
instead should define to_s super:
def to_s super + " [#{@lyrics}]" end
now when @duration variable still stores song duration in miliseconds, how new to_s calls parent's method solve problem? still returns 3750 minutes, doesn't it?
i think dont understand difference between 2.
it's assumed song
take care of proper output of @duration
.
and if decide change song
store duration in milliseconds, change song#to_s
method , won't have change to_s
of descendants.
Comments
Post a Comment