Monkey-patching with modules

module Foo
class String
def hi
puts ‘hi’
end
end
end

include Foo

x = “hello”
x.hi

Why does this not work?

Thanks.

Mike H. wrote:

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’.

On Dec 24, 2007 4:08 PM, Mike H. [email protected] wrote:

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)


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Thanks very much.

On Dec 24, 2007, at 4:18 PM, Rick DeNatale wrote:

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

On Dec 24, 9:44 pm, thefed [email protected] wrote:

Thanks,
aRi

Class variable?

Regards,
Jordan

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs