On Wed, Jul 9, 2008 at 11:22 AM, Clement Ow [email protected] wrote:
And in my main script I have something like:
But apparently it shows an error:
undefined method `toDDMMYYYY’ for #<Date: 4909313
,2299161> (NoMethodError)
Did do wrongly in calling the class methods, maybe I am confused with
the syntax of calling class methods? Much help is appreciated, thanks!
You did not define a class method, actually there are more ways to
implement what you want.
I will show you three here, it is up to you to decide what fits your
needs best
To expand, what Robert means is that you defined an instance method. To
make it a class method in class C, you should C.m or self.m, not m
(which would be an instance method).
Personally I prefer self.m, as I can subsequently change the name of the
class if necessary without having to change all the class method names
too. Laziness can be a virtue.
I think you have 2 different errors in your script:
The error already highlighted by other forum members.
You are creating a class named “Test” and a method for it, and later
on you try to call this method inside an object that belongs to a
totally different class (Date class). If you want to add the new method
to the Date class you only need to write:
class Date
def toDDMMYYYY(sep)
strftime("%d#{sep}%m#{sep}%Y")
end
end
In this way the new method will be available in any date object. You
need to modify your main code too:
class MainLogic
def show_date
d = Date.today
d.toDDMMYYYY("-")
end
end
Rgd,
Nando
Thanks for the replies, it makes Ruby learning so much easier! =)
It does work however if i change the class name to Date instead of test
too. But what if my class is an inherited class? Maybe an example might
explain clearer.
Assuming I have 2 classes:
class MadDate < Date
def toDDMMYYYY(sep = “/”)
strftime(%d%m%Y")
end
end
class Main
def self.show
d = Date.today
d.toDDMMYYYY("-")
end
end
And when i call, Main.show, it gives the same error “undefined method
toDDMMYYYY”. Is there then a way of working around inherited classes?
I think you have 2 different errors in your script:
The error already highlighted by other forum members.
You are creating a class named “Test” and a method for it, and later
on you try to call this method inside an object that belongs to a
totally different class (Date class). If you want to add the new method
to the Date class you only need to write:
class Date
def toDDMMYYYY(sep)
strftime("%d#{sep}%m#{sep}%Y")
end
end
In this way the new method will be available in any date object. You
need to modify your main code too:
class MainLogic
def show_date
d = Date.today
d.toDDMMYYYY("-")
end
end