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.

···

--
Posted via http://www.ruby-forum.com/.

Mike Holly 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'.

···

        def hi
            puts 'hi'
        end
    end
end

include Foo

x = "hello"
x.hi

Why does this not work?

Thanks.

--
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

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)

···

On Dec 24, 2007 4:08 PM, Mike Holly <mikejholly@gmail.com> wrote:

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

include Foo

x = "hello"
x.hi

Why does this not work?

--
Rick DeNatale

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

Thanks very much.

···

--
Posted via http://www.ruby-forum.com/.

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

Class variable?

Regards,
Jordan

···

On Dec 24, 9:44 pm, thefed <fed...@gmail.com> wrote:

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