class String in a module

  • Thread starter Gabriel Dragffy
  • Start date
G

Gabriel Dragffy

Hi all

I have a module file which contains 'class String' and a couple of
custom methods for me to add to Object::String. So I do something like:
require 'mystring' or load or whatever. It doesn't extend String's
functionallity... no doubt because the modules contents are isolated
in their own namespace... How to get around that?


Many thanks




Gabriel Dragffy

(e-mail address removed)
 
S

Stefano Crocco

Alle luned=EC 6 agosto 2007, Gabriel Dragffy ha scritto:
Hi all

I have a module file which contains 'class String' and a couple of
custom methods for me to add to Object::String. So I do something like:
require 'mystring' or load or whatever. It doesn't extend String's
functionallity... no doubt because the modules contents are isolated
in their own namespace... How to get around that?


Many thanks




Gabriel Dragffy

(e-mail address removed)

Do you mean the following situation?

# file mystring.rb

module MyMod

class String
=20
...

end
=20
end

In this case, you're right. This piece of (pseudo) code creates the class=20
MyMod::String, which is a completely different thing from the String class.=
=20
If you want to extend String, you simply have to move the class=20
String;...;end part outside the definition of module MyMod:

# file mystring.rb

class String
=20
...

end

module MyMod
...
end
=20
I hope this help

Stefano
 
J

Joel VanderWerf

Gabriel said:
Hi all

I have a module file which contains 'class String' and a couple of
custom methods for me to add to Object::String. So I do something like:
require 'mystring' or load or whatever. It doesn't extend String's
functionallity... no doubt because the modules contents are isolated in
their own namespace... How to get around that?

Use the global scope operator (at least I think that's what it's called):

module M
class ::String
def backwards; reverse; end
end
end

puts "24".backwards # => 42
 

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,172
Messages
2,570,934
Members
47,478
Latest member
ReginaldVi

Latest Threads

Top