def new(*args)
euro, cent = *args
...
Well, this didn't really answer the OPs question, and is a bit misleading.
calling this with one argument will set euro to ni, and cent to the
argument, which probably isn't what's looked for.
Answering more directly, no Ruby methods are named only by the name,
and there's no notion of overloading with different parameter types.
First an aside, since you named this method new, I'm guessing that you
are talking about creating a new object, this is (probably) another
difference between Ruby and whatever language you have used before.
In ruby the new method is almost never overriden (and it's a class
method anyway so it would be def self.new;end). Instead new objects
are intialized through an instance method called initialize.
Okay, that said there are various techniques to allow for some
variation in parameters to a method.
One is the use of a final argument prefixed by * this collects any
arguments passed left over after any prior arguments are satisfied to
an array. So let's say you were doing a class representing Money
valuated in Euros, and that you wanted EuroMoney.new(10) to create an
object containing 10 Euro cents, and EuroMoney.new(1,50) to represent
1 and 1/2 Euros. You could do this with something like
class EuroMoney
def initialize(*args)
raise ArgumentError unless (1..2).include?(args.length)
@cents = args.last
if args.length > 1
@euros = args.first
else
@euros = 0
end
end
end
Now lets' say instead we want to be more flexible and have a money
class which has both a value and a currency, and you want to specify a
unit amount, and a currency with a default. There are at least two
ways to do this:
1) currency argument with default value:
class Money
def initialize(value, currency = :euros)
@value, @currency = value, currency
end
end
So 1.50 Euros could be created either with:
Money.new(150)
or
Money.new(150, :euros)
and the equivalent <G> in US Dollars would be:
Money.new(1500, :"US$")
2) use a hash argument to get the equivalent of keyword arguments
class Money
def initialize(&args={})
args = {:currency => :euros}.merge args # this
provides a default for currency
@currency = args[:currency]
@value = args[:value]
end
end
A formal parameter with an & prefix is a hash.
So we would have
Money.new
value => 150)
Money.new
currency => :euros, :value => 150)
and
Money.new
currency => :"US$", :value => 1500)
as the equivalents to the previous examples.
The second approach is probably overkill, on the other hand, with some
more coding, one could use it to model more general concepts of money
with more code in the initialize method and support things like:
Money.new
currency =>
ld_imperial_english, :shillings => 10,
ounds
=> 5)
which would compute the unit value based on the components in a flexible
manner.
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/