Monkey-patching with modules

M

Mike Holly

module Foo
class String
def hi
puts 'hi'
end
end
end

include Foo

x = "hello"
x.hi

Why does this not work?

Thanks.
 
J

Joel VanderWerf

Mike said:
module Foo
class String

You are defining a new class, Foo::String.

Try this here instead:
class ::String

The :: means 'look up String in the global scope'.
 
R

Rick DeNatale

module Foo
class String
def hi
puts 'hi'
end
end
end

include Foo

x = "hello"
x.hi

Why does this not work?

A module is a namespace, so constant names defined inside a module are
nested within the module.

You've defined a new class named Foo::String which is not the same
class as String (a.k.a. ::String)
 
T

thefed

A module is a namespace, so constant names defined inside a module are
nested within the module.

Is there some equivalent of a variable constant? I'm looking for a
variable that is shared only within the module but is variable.

Basically, a more restrictive global.

Thanks,
aRi
 
M

MonkeeSage

Is there some equivalent of a variable constant? I'm looking for a
variable that is shared only within the module but is variable.

Basically, a more restrictive global.

Thanks,
aRi

Class variable?

Regards,
Jordan
 

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
474,274
Messages
2,571,367
Members
48,060
Latest member
JerrodSimc

Latest Threads

Top