Complie-time polymorphsim and Run-time polymorpshism

H

hari bhat

Hi

I wanted to know about complie-time polymorphsim
and run-time polymorpshism in ruby

with examples.







Regards,
Hari
 
X

Xavier Noria

Hi

=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0I wa=
nted to know about complie-time polymorphsim
and run-time polymorpshism in ruby

As a rule of thumb Ruby is runtime-only. When you evaluate

obj.method

obj's class is checked at that exact point in the execution of the
program. If you later execute that line again, it is checked again.
And due to the nature of Ruby obj could be an instance of a different
class, or of the same class but with different API than before. You
check it always.

There's a gotcha with core classes though, like Hash and friends. If
you for example subclass Hash, MyHash, and define a custom #[]=3D that's
not seen by the rest of inherited methods. So for example an inherited
MyHash#merge! is still going to use the original Hash#[]=3D.

Reason is Hash is implemented in C and #merge! has hard-coded calls to
the C function that implements Hash#[]=3D. So polymorphism is missing
here. Same with String and others.

It feels a bit strange in an otherwise pure OO language like Ruby, but
as far as I know it is a pragmatic compromise for speed. Rubinius and
JRuby would naturally support that polymorphism, but they don't on
purpose for compatibility with MRI.
 

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

Staff online

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top