Extend initialize method in String Class

Hi

My first Ruby newbie question.

I am trying to extend the String class by
incorporating a VB string class I wrote. In order to
do this I need to add some code the ths String
initialize method. Here is what I’m trying do do:

require ‘win32ole’

class String

def initialize (v)
@s = WIN32OLE.new(‘Apputility.clString’)
@s.assign = v
String.initialize (v)
end

def countOf (v)
@s.countof(v)
end

The user programmer would code something like:
myString = "hello world"
puts myString.countOf(‘o’)
or
myString = String.new(“hello world”)
puts myString.countOf(‘o’)

If I code “myString = String.new(“hello world”)” then
the new initialize method is invoked and the
original is not.
If I code "myString = ‘hello world’ then the original
initialize method is invoked and the new one is not.

Can I extend the initialize method? If so how?

Thanks in advance

Murray

require ‘win32ole’

class String
def initialize (v)
@s = WIN32OLE.new(‘Apputility.clString’)
@s.assign = v
String.initialize (v)
end

def countOf (v)
@s.countof(v)
end
end

Use Module#alias_method.

class String
alias_method :initialize, :initialize

def initialize(v)
  @s = WIN32OLE.new('Apputility.clString')
  @s.assign = v
  __initialize__(v)
end

attr_reader :s

end

However, note that this will only work for cases where you do
String#new directly; it will not work for automatically generated
strings (e.g., s = “foo”).

The user programmer would code something like:
myString = “hello world”
puts myString.countOf(‘o’)
or
myString = String.new(“hello world”)
puts myString.countOf(‘o’)

The user programmer doesn’t need to use the Win32OLE version of
countOf. You can use String#count, though:

“Hello world”.count(“o”) # => 2

-austin
– Austin Ziegler, austin@halostatue.ca on 2003.04.18 at 21:41:18

···

On Sat, 19 Apr 2003 08:35:30 +0900, Bilbo wrote: