lec20 - # a basic class c class PosRat # initialize is...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
# a basic class class PosRat c # initialize is special; immediately called on result of PosRat.new def initialize(num,den=1) # default arguments if num < 0 || den <= 0 raise "PosRat received an inappropriate argument" end @num = num # fields created when you assign to them @den = den reduce end def print STDOUT.print @num if @den != 1 # everything true except false _and_ nil objects STDOUT.print "/" puts @den # a method inherited from Kernel, adds a newline end end def print2 # using some unimportant syntax and simpler algorithm? d = "" d = "/" + @den.to_s if den != 1 puts(@num.to_s + d) end def print3 # using things like Scheme's quasiquote and unquote puts("#{@num}#{if @den==1 : "" else "/" + @den.to_s end}") end def add r a = r.num # only works b/c of protected methods below b = r.den # only works b/c of protected methods below c = @num d = @den @num = (a * d) + (b * c) @den = b * d reduce self # convenient for stringing calls end # a functional addition, dynamic typing means now + works on rationals
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

lec20 - # a basic class c class PosRat # initialize is...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online