subclassing Date class

J

Josselin

Is it possible w Ruby to subclass the Date class in order to inherits
all Date methods and add my own methods and attributes ?

I need to pass an array of Date objects and I'd like to specify if this
date instance is a starting_date or ending_date...

joss
 
J

Jan Friedrich

Josselin said:
Is it possible w Ruby to subclass the Date class in order to inherits
all Date methods and add my own methods and attributes ?
Yes. Even it is possible to extend the Date class with your methods. :)

regards,
Jan
 
S

S Wayne

You can extend pretty much every class in Ruby, or you can add to the
base class itself directly, although this can be dangerous.

I'd recommend just creating your own Class that inherits from Date and
does what you need:

require 'date'

MyDate < Date
attr_accessor :date_type
end

m = MyDate.today
m.date_type='start_date'

m.to_s => "2006-06-30"

m.date_type => "start_date"
 
D

danbernier+ruby

S said:
I'd recommend just creating your own Class that inherits from Date and
does what you need:

The only problem with that is you have to use the MyDate class
everywhere -- if there's a large codebase, that might be a problem. If
you add the methods to Date directly, that problem's solved. Might it
make sense to have a conversion function? I haven't gotten too deep
into this part of the dynamic language landscape yet...
 
J

Josselin

The only problem with that is you have to use the MyDate class
everywhere -- if there's a large codebase, that might be a problem.
can you explain a little bit more ? i am a newrubies
If
you add the methods to Date directly, that problem's solved.
yes, but what about attribute (myDate_type ..)

I solved my problem with a two-dimensional array.. [[date] , [integer]]
but it's like using a hammer to smash a fly.... better add this
integer value in a date subclass ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,206
Messages
2,571,071
Members
47,678
Latest member
Aniruddha Das

Latest Threads

Top