Method Scope (again b/c google groups lost it)

T

Trans

I would like to see Ruby gain a "scoping feature" (I usually refer to
this as a "namespace", but looking at Matz' discussion of Rite he's
using that to mean something else). This idea is this:

class String

scope format

def jumble
...
end

end

end

"Wizard".format.jumble


Currently I can implement like so:

require 'delegate'

class String

def format
@__format__ ||= Format.new( self )
end

class Format < DelegateClass( self )

def jumble
...
end

end

end

But that has a whole lot of icky overhead. I would be nice if Ruby
could support this kind of thing natively. It's a nice way to organize
methods.

T.
 
A

Ara.T.Howard

I would like to see Ruby gain a "scoping feature" (I usually refer to
this as a "namespace", but looking at Matz' discussion of Rite he's
using that to mean something else). This idea is this:

class String

scope format

def jumble
...
end

end

end

"Wizard".format.jumble

harp:~ > cat a.rb
class Dispatch < Hash
def method_missing(m, *a, &b); self[m].call(*a, &b); end
end
class String
def format(*a, &b)
Dispatch[
:jumble => lambda{ 'jumble' },
:bumble => lambda{ 'bumble' },
]
end
end

p "Wizard".format.jumble
p "Wizard".format.bumble


harp:~ > ruby a.rb
"jumble"
"bumble"

easy cheasy. ;-)

-a
--
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| My religion is very simple. My religion is kindness.
| --Tenzin Gyatso
===============================================================================
 
T

Trans

Ara.T.Howard said:
harp:~ > cat a.rb
class Dispatch < Hash
def method_missing(m, *a, &b); self[m].call(*a, &b); end
end
class String
def format(*a, &b)
Dispatch[
:jumble => lambda{ 'jumble' },
:bumble => lambda{ 'bumble' },
]
end
end

p "Wizard".format.jumble
p "Wizard".format.bumble


harp:~ > ruby a.rb
"jumble"
"bumble"

easy cheasy. ;-)

Cleverly done. Certainly reduces the overhaed to an acceptable level.
Too bad it looses all the goodness of OOP inheritence though.

Thanks,
T.
 

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,176
Messages
2,570,949
Members
47,500
Latest member
ArianneJsb

Latest Threads

Top