I don't understand why when I try to overload I get an error. Can I
overload somehow?
Hi Ted,
sorry no overloading in ruby. overloading gives fixed/absolute power
to compiler/interpreter. ruby is dynamic, everything can be changed at
runtime, anytime. second, ruby is oo, ojbect first progg,
polymorph-based ie.
def sum(x)
return x + 2
^^
lose the return, ruby does not need it here
as others have mentioned, you can use starred args and default params
to mimic overloading. if that does not fit your taste, you can use
named params or hash (it fits mine
the advantage of named params over static signature/position-based
param is that you have more control of your method since it is really
*the* params (wc are objects by themselves) that do the playing, not
the positioning (again, emphasizing o-o-ness). ergo, you have better
control and you can test/debug the methods a lot better.
now if that still does not suit your taste, you can do polymorphism,
wc of course comes natural in o-o langgs.
anyway, the ff code shows how to scheme thru named parameters way,
eg,
class Summer
def sum(opt={:none=>"none entered :)"})
case opt.keys.sort
when [:none]
opt[:none]
when [:x]
sumx opt[:x]
when [:x, :y]
sumxy opt[:x], opt[:y]
when [:x, :y, :z]
# you can place more conditions here
sumxyz opt[:x], opt[:y], opt[:z]
when [:a, :x, :y, :z]
sumxyz_xa opt[:x], opt[:y], opt[:z], opt[:a]
else
# you can place other conditions and methods here, do anything
end
end
private
def sumx x
x + 2
end
def sumxy x,y
x + y
end
def sumxyz x,y,z
x + y + z
end
def sumxyz_xa x,y,z,a
sumxyz(x,y,z) ** a
end
end
#=> nil
s = Summer.new
#=> #<Summer:0x918e350>
puts s.sum()
none entered
#=> nil
puts s.sum(x:3)
5
#=> nil
# note also that the params have been disarranged to show flex
puts s.sum(x:3,y:4)
7
#=> nil
puts s.sum(z:5,x:3,y:4)
12
#=> nil
# this last sample call previous method and raises that to power :a
puts s.sum(y:4,a:6,x:3,z:5)
2985984
#=> nil
best regard -botp
···
On Fri, Jan 28, 2011 at 3:22 AM, Ted Flethuseo <flethuseo@gmail.com> wrote: