[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Monkey-patching with modules

Mike Holly

12/24/2007 9:09:00 PM

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

5 Answers

Joel VanderWerf

12/24/2007 9:17:00 PM

0

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

Rick DeNatale

12/24/2007 9:18:00 PM

0

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?

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

Mike Holly

12/24/2007 9:49:00 PM

0

Thanks very much.
--
Posted via http://www.ruby-....

fedzor

12/25/2007 3:44:00 AM

0


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

MonkeeSage

12/25/2007 3:35:00 PM

0

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

Class variable?

Regards,
Jordan