Inheritance from built-in class

  • Thread starter Nicolaj Soendberg-Madsen
  • Start date
N

Nicolaj Soendberg-Madsen

I have a question regarding inheritance from built-in classes. To simplify
it, say I want to create a time-stamped array, which is an array with a
time-stamp. Then I want to override the to_s method. I tried the following
code:


class Time_stamped_array < Array
def initialize
@time_stamp = Time.now
end

def to_s
super + " #{@time_stamp}"
end

end

ta = Time_stamped_array.new

puts ta.to_s


However this last call seems to invoke to_s in the super class (Array)
and not in my new class. How do I do what I intented to do instead?
Isn't it possible to override built-in methods?

Thanks in advance.
 
T

ts

N> puts ta.to_s

This line work, but probably you have written

puts ta

and ruby has not called Time_stamped_array#to_s, no ?

N> However this last call seems to invoke to_s in the super class (Array)

#puts has a special case for object which respond to #to_ary (like Array)


Guy Decoux
 
D

daz

Nicolaj said:
I have a question regarding inheritance from built-in classes. To simplify
it, say I want to create a time-stamped array, which is an array with a
time-stamp. Then I want to override the to_s method. I tried the following
code:


class Time_stamped_array < Array
def initialize
@time_stamp = Time.now
end

def to_s
super + " #{@time_stamp}"
end

end

ta = Time_stamped_array.new

puts ta.to_s


However this last call seems to invoke to_s in the super class (Array)
and not in my new class. How do I do what I intented to do instead?
Isn't it possible to override built-in methods?

That should be working, but your Time_stamped_array is empty
so only the date appears, I guess (?)


class Time_stamped_array < Array
def to_s
super + " #{Time.now}"
end
end

ta = Time_stamped_array.new
ta.push('ab') # add to Time_stamped_array
ta.push('cd') # - another -
p ta #-> ["ab", "cd"]

puts ta.to_s #-> abcd Thu Aug 26 09:10:11 ...


:daz
 

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

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top